Search code examples
cshellunixforkpid

Fork function doesn't return 0 value?


When i call fork() in main.I don't get 0 value for child process id. My code :

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

int main(){


    pid_t pid = fork();
    printf("pid in child=%d and parent=%d\n",getpid(),getppid());       
    wait(NULL);

}

And the output :

pid in child=15690 and parent=11593
pid in child=15691 and parent=15690

Where is the problem? As i know i should have got 0 value for child process in the second line.


Solution

  • You should actually use the value of pid in your printf statement.

    The result of fork() is zero for the forked process, but its process id as gained by getpid() is not zero.