问题
Hi all I have to run a binary file using c++ and kill it.
My code look like
static int PROCESS_PID=0;
void startService(bool startservice){
if(startservice==true){
pid_t PID = fork();
if(PID == 0) {
PROCESS_PID = getpid();
printf("the child's pid is: %d\n", PROCESS_PID);
system("./process");
}
}
else{
kill(PROCESS_PID, SIGUSR1); //kill process inside child process
}
}
But when I kill the process the entire program get exited. Any Idea ? Is there anything wrong with my code ?
Thanks....
回答1:
When you call system()
you are starting a third process -- one which you do not have the pid for. Use exec()
instead.
Worse though, your kill()
call is only made in the case that startservice!=true
, and in this case PROCESS_PID==0
... so you're killing process 0 (which will send the signal to all processes in your current process group).
回答2:
The reason it's not working is because you are double-fork()
ing, as system()
will perform a fork()
/exec()
in order to execute the command you want to run.
If you want better control of the child process (including killing it) then write your own version of system()
where you perform the fork()
and exec()
yourself.
There are many examples of how to do this knocking around the internet.
来源:https://stackoverflow.com/questions/18697493/fork-how-to-kill-a-process-with-pid