Alex.P Alex.P - 1 month ago 9
C Question

How to know if a process is a parent or a child

Hi i'm currently interested in linux kernel system and i'm trying to identify if a process is a child/grandchild of another process using the pids can someone help me with this please

Answer

Checking whether or not a process is the child of another

Whenever fork() is called the process in which the fork() statement is executed spawns a child process.

In a program that has yet to call fork() has only one running process, or one unit of execution.

When fork() returns, there are two processes running concurrently.

Both of these processes have the same call-stack immediately after fork() returns. In the parent process, the return value of fork() is the PID of the child process. In the child process, the return value of fork() is 0.

This is easily demonstrated by the following code-snippet.

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

int main(){
    pid_t parent = getpid();
    pid_t child = fork();

    if (child == 0) {
        printf("I am the child process. My PID is %d\n", getpid());
        printf("\t My parent's PID is %d\n", parent);
        printf("\t which can also be retrieved using getppid(): %d\n", getppid());
        printf("\t Child process terminating\n");
    } else {
        printf("I am the parent process. My PID is %d\n", parent);
        printf("\t which can also be retrieved using getpid(): %d\n", getpid());

        printf("\t Parent process terminating\n");
    }

    return 0;
}

Sample output:

➜  ~ ./a.out                 
I am the parent process. My PID is 13728
     which can also be retrieved using getpid(): 13728
     Parent process terminating
I am the child process. My PID is 13729
     My parent's PID is 13728
     which can also be retrieved using getppid(): 13728
     Child process terminating

The PID numbers may vary each time you run the program. The execution-order between the two processes is not guaranteed meaning that the parent process will return to the shell before the child process has finished, which is why we traditionally use waitpid().

Checking if a process is the "main" process

One can use syscall to find out whether or not a process is the "main" one like so,

#define _GNU_SOURCE

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

int main(){
    if (getpid() == syscall(SYS_gettid)) {
        printf("I am the \"main\" process: %ld\n", syscall(SYS_gettid));
    }
    return 0;
}

Sample output:

➜  ~ ./a.out                 
I am the "main" process: 13969