Killing a process with C program

Viewed 2310

I'm writing a program that open a .txt file by vim and whenever i press CTRL+C the process will be killed. But the thing is i can't find the process's pid that i've just created and kill it. Can anybody 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){}
    
}
1 Answers

There are multiple issues with your code:

  • system(3) does NOT return PID of child process, but instead waits for it to exit, and returns its exit code. You need to use the traditional fork+exec approach.
  • With child PID available, it's easier to call kill(2) than kill(1)
  • Better add sleep in a dead loop waiting for input. This reduces CPU load and your electricity bill.
#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