0

I know that it can be either of these. But I always see that the parent executes first on my LINUX terminal.

  • I used the same code on two different machine, one use kali Linux and the other Ubuntu , I got the same result.
  • I searched for that and I got nothing.

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>

int main(){
    int id = fork();
    if(id == -1) {
        printf("error!");
        return 1;
        }

    if(id == 0){
        printf("I'm the child\n");
        printf("child\n");
        return 2;
    }else{
        printf("I'm the parent\n");
        wait(NULL);
        printf("child has terminated\n");
        return 3;
    }
   return 0;
}

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 3
    It's not specified, and it really can be either. Even if it always seems to be the same one, you should not even think of writing code that depends on them running in a specific order. – Barmar May 12 '22 at 20:10
  • 1
    "I know that it can be either of these." That's the answer. The parent is likely to continue executing while the child process is spun up, but there's no guarantee. It could be preempted at any time, or it could run slower than the child for whatever reason. – John Kugelman May 12 '22 at 20:11
  • If the computer has multiple CPUs, they can both run simultaneously. – Barmar May 12 '22 at 20:11
  • 1
    Here the situation is opposite: https://ideone.com/SHk9p7 – Eugene Sh. May 12 '22 at 20:14
  • I'm asking why the parent in Linux has a high winning probability – Hicham Zakroum May 12 '22 at 20:24
  • @EugeneSh. Not really, it is just because the output is not to a terminal and therefore fully buffered. Remove buffering and the situation becomes normal again [demo](https://ideone.com/M1V0cX) – n. m. could be an AI May 12 '22 at 20:26
  • "I'm asking why the parent in Linux has a high winning probability". Because creating a new process *takes time*. – n. m. could be an AI May 12 '22 at 20:28
  • @n.1.8e9-where's-my-sharem. Well, one could claim that your change is changing the scheduling :) I won't, as I don't know and suspect that you are probably right. – Eugene Sh. May 12 '22 at 20:32
  • I ran `strace` couple of times, in all the cases `vfork` system call was made after `openat` by parent pid `getpid`, which I believe is the `printf("I'm the parent\n");`. I'm no `c-lang` expert but just trying out `strace` to learn system calls & program behavior.. – harshavmb May 12 '22 at 20:36

0 Answers0