-1
#include <stdio.h>
#include <stdlib.h> // exit
#include <unistd.h> // fork, getpid

int main(int argc, char *argv[])
{
    printf("hello world (pid:%d)\n", (int) getpid());
    int ret_fork = fork();
    if (ret_fork < 0) {
        // fork failed; exit
        fprintf(stderr, "fork failed\n");
        exit(1);
    } else if (ret_fork == 0) {
        // child (new process)
        printf("hello, I am child (pid:%d)\n", (int) getpid());
    } else {
        // parent goes down this path (original process)
        printf("hello, I am parent of %d (pid:%d)\n",
           ret_fork, (int) getpid());
    }
    return 0;
}

When I excute this, I got:

hello world (pid:3082)
hello, I am parent of 3083 (pid:3082)
hello, I am child (pid:3083)

Why are second row is printed faster than third row?

I want to know how it works in sequence.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
whynot
  • 29
  • 2

2 Answers2

0

When you use new processes, they all run separately. Your terminal window can only output one at a time, so whichever one gets in first will be put out first. If you run it several times, you may find out that other processes get outputed first, it's just random.

KaliMachine
  • 191
  • 9
0

The order is not defined and you shouldn't rely on any order:

While you cannot control which process (parent or child) gets scheduled first after the fork (in fact on SMP/multicore it might be both!) there are many ways to synchronize the two processes [...]

From Can the order of execution of fork() be determined?

If you need, you should synchronize the two processes with other means.

Marco
  • 7,007
  • 2
  • 19
  • 49