Ren
Ren

Reputation: 4683

Code (with fork) that shouldn'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.

Upvotes: 2

Views: 116

Answers (2)

Sandeep
Sandeep

Reputation: 19452

If you are not aware of fork() and using it, it is dangerous.

This is one of the basic system calls in Linux used for creating a new process. Refer to Man page to know what it does. And here is one helpful link to make you understand better. fork(). To know more about it you could also refer here- fork() wiki. It uses methods like copy-on-write and shares the resources with child.

Once you have used fork() to create the new process, you can use exec(...) to change the program that the process is executing. After reading about each of them, you may refer to this post on so.

Upvotes: 1

Matthew Adams
Matthew Adams

Reputation: 10126

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.

Upvotes: 6

Related Questions