ell
ell

Reputation: 25

why is child process running code meant for parent

The snippet below is being run by the child process as well but I don't know why because to my understanding the child's Pid should always be 0 so there's no reason for it to ever do anything below but print "I am child";

 pid_t child_Pid1 = fork();

 if((int)getpid() == 0) {
 printf("I am child\n");
 } else {
    printf("I am parent\n");
    }

Upvotes: 2

Views: 78

Answers (1)

Nate Eldredge
Nate Eldredge

Reputation: 58493

getpid() always returns the current process's pid which is never zero, so in your current code, neither of the two processes does the execlp.

You want to look at child_Pid1 instead of getpid(). In the child it returns 0 instead of the child's pid.

Upvotes: 3

Related Questions