I am trying to better understand fork(), waitpid() and child/parent processes, however there are some strange behaviors I have encountered with the following code:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void){ // Main
int status;
pid_t wPID, cPID;
printf("[%i] Hi I am the parent and I am about to create a child...\n", getpid());
fflush(0);
pid_t childPID = fork();
if (childPID >= 0){
if(childPID == 0){ //child process
cPID = getpid();
printf("[%i] %i\n", getpid(), cPID );
printf("[%i] Hi, I am the child process...\n", getpid() );
sleep(1);
for(int i = 0; i<3; i++){
printf("[%i] %i\n", getpid(), i);
}
exit(0);
}
else{ //parent
printf("[%i] %i\n", getpid(), cPID );
wPID = waitpid(cPID, &status, 0);
printf("[%i] value returned by waitpid: %i\n", getpid(), wPID);
if (WIFEXITED(status))
printf("[%i] child exited, status=%d\n", getpid(), WEXITSTATUS(status));
else if (WIFSIGNALED(status))
printf("[%i] child killed (signal %d)\n", getpid(), WTERMSIG(status));
else if (WIFSTOPPED(status))
printf("[%i] child stopped (signal %d)\n", getpid(), WSTOPSIG(status));
else /* Non-standard case -- may never happen */
printf("Unexpected status (0x%x)\n", status);
return 0;
}
}
else{
printf("\n Fork failed, quitting!\n");
return 2; // error
}
}
console output:
$ ./waitpidexample [6103] Hi I am the parent and I am about to create a child... Error: No child processes [6103] 1540418008 [6103] value returned by waitpid: -1 [6103] child killed (signal 54) [6104] 6285 [6104] Hi, I am the child process... [6104] 0 [6104] 1 [6104] 2
I believe my issue is in the cPID variable being used in waitpid()...
there is some sort of scope issue happening here, as it evaluates to different values in the child / parent.
How am I supposed to get the correct child process id for use in waitpid()?
Why is the code after my waitpid() being executed before the code in the child process?
childPID
, notcPID
... – Oliver CharlesworthError: No child processes
. Although that could be because of the undefined behavior you have when doingfflush
with a null pointer. – Some programmer dudewaitpid
returns with an error (in the case of many system functions indicated by a return of-1
) then you need to checkerrno
to figure out what happened. And you need to do it immediately, you can't call any function which might altererrno
in between. – Some programmer dude