Fork如何使用PID杀死进程 [英] Fork How to Kill A process with PID
问题描述
我只需要使用c ++运行一个二进制文件并杀死它.
Hi all I have to run a binary file using c++ and kill it.
我的代码看起来像
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 ?
谢谢....
推荐答案
当您调用 system()
时,您将启动第三进程-您没有pid的进程.改用 exec()
.
When you call system()
you are starting a third process -- one which you do not have the pid for. Use exec()
instead.
不过,更糟糕的是,仅在 startservice!= true
的情况下进行您的 kill()
调用,在这种情况下,此调用 PROCESS_PID == 0 代码> ...所以您要杀死进程0(它将信号发送到当前进程组中的所有进程).
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).
这篇关于Fork如何使用PID杀死进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!