It gives me the parent process as 707 always! Should it it be giving the pid1 id?

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

int main() {
    pid_t pid1 = getpid();
    printf("the parent id is %d \n", pid1);

    if (pid1 % 2 != 0) {
        printf("the parent id is odd\n");

    } else {
        printf("%d\n", getpid());
        printf("its even two childs were created\n");
        int i = fork();

        if (i == 0) {
            printf("child 1 chiled id is %d, parent is %d\n", getpid(),
                   getppid());

        } else {
            int i2 = fork();
            if (i2 == 0) {
                printf("child 2 chiled id is %d, parent is %d\n", getpid(),
                       getppid());
            }
        }
    }
}
the parent id is 6560 
6560
its even two childs were created
child 2 chiled id is 6562, parent is 707
child 1 chiled id is 6561, parent is 707
1

There are 1 answers

0
Oka On

Your parent process does not wait for its child processes, and is very likely to terminate before they have a chance to call getppid. When a parent process terminates before its children, the child processes become orphan processes.

In Linux, orphan processes are either reparented to the init process (PID 1), or the nearest ancestor subreaper process, which performs the necessary task of reaping the child process when it terminates. It would appear on your machine a subreaper is being employed, and that's the ID being returned by getppid.

(See also prctl(2), PR_SET_CHILD_SUBREAPER / PR_GET_CHILD_SUBREAPER.)

(The command ps -p 707 would also give information about the process acting as the subreaper.)

You need a construct like

while (wait(NULL) > 0)
    /* very basic example */;

at the bottom of the parent process to properly wait for and reap the child processes.