0

Output and Reasoning

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    int x=10, y=20, z=30;

    printf("Message 0 : x=%d, y = %d, z = %d\n", x,y,z);
    x=fork();
    y=fork();
    if (x != 0) printf("Message 1 : x=%d, y = %d, z = %d\n", x,y,z);
    if (y != 0) printf("Message 2 : x=%d, y = %d, z = %d\n", x,y,z);

    z=fork();
    if ((x>0) || (y>0) || (z>0)) printf ("Message 3 : x=%d, y=%d, z= %d\n", x,y,z);

    if ((x==0) && (y==0) && (z!=0)) printf ("Message 4 : x=%d, y = %d, z=%d\n",x,y,z);
    if ((x!=0) && (y!=0) && (z!=0)) printf ("Message 5 : x=%d, y=%d, z=%d\n",x,y,z);
}

Above is a code that I compiled in Unix. The picture I attached is how I see the forks creating the processes.

My question is how do I decide which is a parent process and which is a child process? If there is anything wrong with my picture do tell me too.

Ayush Bherwani
  • 2,409
  • 1
  • 15
  • 21
  • 5
    Read the manual. Parent is the one where fork() returns a nonzero value. – Petr Skocik Oct 24 '18 at 14:36
  • 2
    ...and format your code correctly. – Jabberwocky Oct 24 '18 at 14:40
  • Note that some of the eight processes are both a child and a parent process at the same time. – Jonathan Leffler Oct 24 '18 at 15:01
  • Please don't post text output as an image. All the information needed to answer the question should be in the question. You can clarify your output by adding the PID of the current process and its parent PID (`getpid()` and `getppid()`) to each `printf()` statement. Consider using `fflush(stdout)` after each print too. You should be more consistent in the way you format your numbers (you have `y=%d` and `y = %d` — choose one and stick with it rigorously; using `%5d` would make things align better for easier reading). – Jonathan Leffler Oct 24 '18 at 15:05
  • See also [`printf()` anomaly after `fork()`](https://stackoverflow.com/questions/2530663/printf-anomaly-after-fork). – Jonathan Leffler Oct 24 '18 at 15:07

0 Answers0