C – Kills a process with C program

Kills a process with C program… here is a solution to the problem.

Kills a process with C program

I’m writing a program that opens a .txt file via vim and whenever I press CTRL+C, the process is terminated. But the problem is that I can’t find the pid of the process I just created and killed it. Can anyone help me?

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

void ctrl_C(int sig){
    system("kill -9 $(pidof id)");
    printf("\n You pressed Ctrl + C,Good Bye \n");
    exit(0);    
}

int main(){
    printf("I am Programmer \n");
    pid_t id = system("gnome-terminal -- vi abcd.txt"); 
    signal(SIGINT,ctrl_C);
    while(1){}
    
}

Solution

There are multiple issues with your code:

  • system(3) does not return the PID of the child process, but waits for it to exit and returns its exit code. You need to use the traditional fork+exec approach.
  • With the available sub-PIDs, it is easier to call kill(2) than kill(1).
  • It’s best to add sleep to an endless loop waiting for input. This reduces CPU load and electricity bills.
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

pid_t child_id;

void ctrl_C(int sig){
    kill(child_id, 9);
    printf("\n You pressed Ctrl + C,Good Bye \n");
    exit(0);    
}

int main(){
    printf("I am Programmer \n");
    pid_t child_id = fork();
    if (child_id == 0) {
        execlp("gnome-terminal", "gnome-terminal", "--", "vi", "abcd.txt", NULL);
        return 255;
    }
    signal(SIGINT,ctrl_C);
    while (1) {
        sleep(1);
    }
}

Related Problems and Solutions