Hello. I will ask for help in solving the problem.

The task:

The parent process creates two children. Each of them prints its process ID, after which the parent process prints "Hello world". Used functions: fork (), wait (), exit ().

My code is:

pid_t p1, p2; int status1, status2; switch (p1 = fork()) { case -1: perror("Error fork"); return 1; case 0: printf("Child, pid=%d\n", getpid()); } switch (p2 = fork()) { case -1: perror("Error fork"); return 1; case 0: printf("Child, pid=%d\n", getpid()); } waitpid(p1, &status1, 0); waitpid(p2, &status2, 0); printf("Hello World"); 

At the exit:

  1. Child, pid = 5629
  2. Child, pid = 5630
  3. Hello WorldChild, pid = 5631
  4. Hello WorldHello WorldHello WorldPress to close this window ...

Point out the error please.

  • one
    A specific solution has already been noted. A common mistake was understanding fork logic. First, the "head" was double-forked, then the first copy was forked, since after working it continued to do the same as the parent process. Then all four (head + children) of the obtained process were gladly informed - "Hello world". - Yevgeny Borisov

1 answer 1

After you have forked the process, you first perform

 printf("Child, pid=%d\n", getpid()); 

and then the rest of the program continues (including the output of "Hello, World"). Put after printf (..); exit from the program:

 printf("Child, pid=%d\n", getpid()); exit(0); 
  • Everything is working. Thank. - John