Working with these system calls, but I'm stuck in this code:
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> main() { pid_t pid; switch(pid = fork()) { case -1: printf("fork failed"); break; case 0: //first child printf("\ni'm the first child, my pid is %d", getpid()); fflush(stdout); break; default: //parent sleep(5); /** sleep is generating problems **/ printf("\ni'm the parent process, my pid is %d", getpid()); printf("\ngenerating a new child"); fflush(stdout); switch(pid = fork()) { case -1: printf("fork failed"); break; case 0: //second child printf("\nhere i am, the second child, my pid is %d", getpid()); break; default: //parent wait((int *)0); printf("\nback to parent, my pid is %d", getpid()); } } return 0; }
The output I get is:
i'm the first child, my pid is 6203
i'm the parent process, my pid is 6202
generating a new child
back to parent, my pid is 6202
Process returned 0 (0x0) execution time: 5.004 s
Press ENTER to continue
here i am, the second child, my pid is 6204
What I'm trying to do is a simple fingerprint of these messages controlling synchronization via sleep() . I canβt understand why the program returns before printing the second child message. The default case (one immediately after the second fork) was printed before its child (second) output action, as it ignores its wait() . Therefore, his child was printed after the return process.
I could not understand what the problem was. I noted the sleep () function, because if I replace it with wait((int *)0); , the flux process works the way it was designed (in any case, without any time). At the moment, I'm no longer sure about the process flow or the use of sleep () (pages with people were not useful, too briefly, to be honest).
source share