Search code examples
cprocessforkpidchild-process

C Child process creation


I am writing a program that creates a two processes directly from the parent. My expected output looks like

Main programs process ID: 2834
Child 2 (ID: 2836) Start Sequence at: 23
Child 1 (ID: 2835) Start Sequence at: 20

My actual output is

Main programs process ID: 2834
Child 2 (ID: 2834) Start Sequence at: 23
Child 1 (ID: 2835) Start Sequence at: 20

My code is

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

int main(int argc, char *argv[])
{
   pid_t pid;
   int n;

    if (argc == 1) {
        fprintf(stderr,"Usage: ./a.out <starting value>\n");
        return -1;
    }
    n = atoi(argv[1]);

    int p_pid;
    p_pid = getpid();

    printf("Main programs process ID: %d\n", p_pid); 

    pid = fork();

    if(pid == 0){
       int c1;
       c1 = getpid();
       printf("Child 1 (ID: %d) Start Sequence at: %d\n", c1, n);
    }

    if(pid != 0){
       int c2;
       c2 = getpid();
       printf("Child 2 (ID: %d) Start Sequence at: %d\n", c2, n+3);
    }
    return 0;
}

I am getting the correct child 1 process but not the correct child 2 process. What am I doing wrong or how can I fix this issue?


Solution

  • fork() doesn't create 2 new processes. It spawns 1 child from the main process. It returns 0 inside the child process and the PID of the child if you're in the parent.

    So in your code, when you think you're in child 2 - that's still the parent. You'll need to call fork() again but only inside the parent process.