Search code examples
cprocesssignals

kill(pid,SIGTERM) terminates child process, although pid is of parent


I'm learning about process allocation.

Take this code block for example:

int main(){
    pid_t pid = fork();
    if(pid == 0){
        while(1)
            printf("Child ");
    } else {
        for(int i = 0; i<1000;i++)
            printf("Parent ");
        kill(pid,SIGTERM);
        printf("\n%d \n ", pid);
    }
}

pid = 0 is the child process, pid > 0 is the parent process. kill(pid,SIGTERM) is executed by the parent with it's own pid, yet it kills the child and not itself. Why?


Solution

  • As @Siguza mentioned in the comments, you should re-read the documentation of fork. fork returns a positive value of pid to the parent process. That value is the PID of the child process. Therefore, kill(pid, SIGTERM) sends the signal to the child and not the parent.