ladookie
ladookie

Reputation: 1371

forking and pid

The code:

int main(void) 
{
    printf("pid: %d\n", getpid());
    pid = fork();


    if (pid < 0) {
        fprintf(stderr, "Fork Failed!");
        exit(-1);
    } else if (pid == 0) {
        execv("sum", argv);
    } else {
        printf("  pid: %d\n", pid);
        wait(NULL);
    }
}

The output:

pid: 280
   pid: 281

The question:

Why are the two pid's different. I thought they should be the same because the parent is what is executing in the else block and the parent is what is executing before the fork so they should be the same, no?

Upvotes: 2

Views: 257

Answers (2)

tylerl
tylerl

Reputation: 30877

I won't repeat nos's answer, as he's entirely correct. But I'd point out that any program can retrieve it's own PID with the getpid system call. So there's no reason for the fork to return you own PID. Instead, you may want to know the PID of the process you just forked off, which may be difficult to obtain if it wasn't returned (to the parent) by fork.

Upvotes: 2

nos
nos

Reputation: 229344

RETURN VALUE
       On success, the PID of the child process is returned in the parent, 
       and 0 is returned in the child.  On failure, -1 is returned in the parent,
       no child process  is  created,  and  errno  is  set appropriately.

So, in the parent process, fork() returns the pid of the child process that was created.

Upvotes: 10

Related Questions