Yokhen Yokhen - 2 months ago 6
C Question

Code that should't loop is looping

So I have the following C code:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(){
int i = 0, n;
n = 5;
pid_t pid;
printf("i=%d Right before the loop\n", i, getpid(), getppid());
for (i = 0; i < n; i++){
pid = fork();
if (pid <= 0){
printf("something happens in loop #%d. pid = %d\n", i, pid);
break;
}
printf("End of loop #%d\n", i);
}

printf("i=%d My process ID = %d and my parent's ID = %d\n", i, getpid(), getppid());

return 0;
}


I have only one question:
Why does

printf("i=%d My process ID = %d and my parent's ID = %d\n", i, getpid(), getppid());


get executed many times as if it was inside the loop? I have tried to figure out through so many ways but I cannot find the reason.

Answer

The reason is that fork() works by making a child process that is a copy of the parent that starts running at the fork() call. So every child process runs that printf command.

Example:

Here's a less complicated example:

#include <stdio.h>

int main(){
  int pid = fork();

  if (pid == 0){
    // child code    
    printf("child pid: 0\n");

  }else{
    // parent code
    printf("parent pid: %d\n", pid);
  }

  // executed by both
  printf("This text brought to you by process %d.\n", pid);
}

You have to do something like this if you want to restrict some code to only be run by the child or parent.

On my machine, when I just ran it, it outputs:

parent pid: 12513
This text brought to you by process 12513.
child pid: 0
This text brought to you by process 0.

My operating system ran the parent process first, but it didn't have to.

Comments