Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c fork's child ppid does not match parent's pid

Tags:

c

fork

I'm totally new to C. I tried the following code, expecting that the child's ppid would match the parent's pid, but this is not the case.

int main() {


    int pid;

    printf("I'm process with pid=%d\n", getpid());

    switch (pid = fork()) {
        case -1:
            perror("fork");
            exit(1);
        case 0:
            printf("I'm the child process: pid=%d, ppid=%d\n", getpid(), getppid());
            break;
        default:
            printf("I'm the parent process: pid=%d, ppid=%d\n", getpid(), getppid());
            break;
    }

    exit(0);

}
> gcc -o fork fork.c 
> ./fork 
I'm process with pid=16907
I'm the parent process: pid=16907, ppid=6604
I'm the child process: pid=16908, ppid=1 // <-- expected ppid=16907, why 1?
>

What did I do wrong ?

like image 295
ling Avatar asked Jul 06 '15 04:07

ling


People also ask

Can PID and PPID be the same?

The PPID is the PID of the process's parent. For example, if process1 with a PID of 101 starts a process named process2, then process2 will be given a unique PID, such as 3240, but it will be given the PPID of 101. It's a parent-child relationship.

What is the parent process ID PPID of a child process whose parent terminates before the child?

most often the parent terminates before the child and the child becomes an orphan process adopted by init (PID = 1) and therefore reports PPID = 1.

What PID does a child process have?

The child process has a unique process ID (PID) that does not match any active process group ID. The child has a different parent process ID, that is, the process ID of the process that called fork(). The child has its own copy of the parent's file descriptors.

Does a child process always have a PID of 0?

The child process's pid is never zero. fork returns zero to the child to tell it that it is the child. The child process's pid, however, is the value that fork returns to the parent. (Remember that fork , assuming it succeeds, returns twice -- once in the child, once in the parent.)


2 Answers

It is likely the parent process has already exited and no longer exists. You could try some delay in the parent.

like image 166
user3344003 Avatar answered Sep 28 '22 13:09

user3344003


'init' which is the root process running in a linux system has pid 1 .

When a process's parent gets terminated before itself(i.e. the child) , the child becomes an 'orphan' process and is taken up by the root process or the process just above the hierarchy of the process which created it(parent process) .

Hence , here it is taken up by and executed under init which has pid = 1 . So, delay your parent process for solution.

like image 34
Harsh Khatore Avatar answered Sep 28 '22 12:09

Harsh Khatore