C语言 如何通过父进程杀死子进程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6501522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to kill a child process by the parent process?
提问by miraj
I create a child process using a fork(). How can the parent process kill the child process if the child process cannot complete its execution within 30 seconds? I want to allow the child process to execute up to 30 seconds. If it takes more than 30 seconds, the parent process will kill it. Do you have any idea to do that?
我使用fork(). 如果子进程不能在30秒内完成执行,父进程如何杀死子进程?我想让子进程最多执行 30 秒。如果超过 30 秒,父进程将杀死它。你有什么想法可以这样做吗?
回答by Mikola
Send a SIGTERM or a SIGKILL to it:
向它发送 SIGTERM 或 SIGKILL:
http://en.wikipedia.org/wiki/SIGKILL
http://en.wikipedia.org/wiki/SIGKILL
http://en.wikipedia.org/wiki/SIGTERM
http://en.wikipedia.org/wiki/SIGTERM
SIGTERM is polite and lets the process clean up before it goes, whereas, SIGKILL is for when it won't listen >:)
SIGTERM 是礼貌的,让进程在它开始之前清理干净,而 SIGKILL 用于它不听的时候 >:)
Example from the shell (man page: http://unixhelp.ed.ac.uk/CGI/man-cgi?kill)
来自 shell 的示例(手册页:http: //unixhelp.ed.ac.uk/CGI/man-cgi?kill)
kill -9 pid
杀死 -9 pid
In C, you can do the same thing using the kill syscall:
在 C 中,您可以使用 kill 系统调用执行相同的操作:
kill(pid, SIGKILL);
See the following man page: http://linux.die.net/man/2/kill
请参阅以下手册页:http: //linux.die.net/man/2/kill
回答by Abhijit
Try something like this:
尝试这样的事情:
#include <signal.h>
pid_t child_pid = -1 ; //Global
void kill_child(int sig)
{
kill(child_pid,SIGKILL);
}
int main(int argc, char *argv[])
{
signal(SIGALRM,(void (*)(int))kill_child);
child_pid = fork();
if (child_pid > 0) {
/*PARENT*/
alarm(30);
/*
* Do parent's tasks here.
*/
wait(NULL);
}
else if (child_pid == 0){
/*CHILD*/
/*
* Do child's tasks here.
*/
}
}
回答by jbruni
In the parent process, fork()'s return value is the process ID of the child process. Stuff that value away somewhere for when you need to terminate the child process. fork() returns zero(0) in the child process.
在父进程中,fork() 的返回值是子进程的进程ID。当您需要终止子进程时,将该值放在某处。fork() 在子进程中返回零(0)。
When you need to terminate the child process, use the kill(2) function with the process ID returned by fork(), and the signal you wish to deliver (e.g. SIGTERM).
当您需要终止子进程时,请使用kill(2) 函数和fork() 返回的进程ID 以及您希望传递的信号(例如SIGTERM)。
Remember to call wait() on the child process to prevent any lingering zombies.
请记住在子进程上调用 wait() 以防止任何挥之不去的僵尸。

