向多个进程发送终止信号后等待一次?
因此,我正在为我的一个编程课程开发一个项目,该作业的一部分是关于能够在后台启动进程,并能够在用户输入“endb”时杀死它们。
为了杀死后台进程,我有一个数组(PIDpool)来保存所有进程的PID,每当用户输入“endb”时,我都会遍历这个PID数组并一一杀死它们。
不过,为了使其正常工作,我必须在向每个进程发送终止信号后添加一个等待。如果我不这样做,就会留下一个已失效的进程,如果我为每个终止信号放置一个等待(通过将等待放在终止循环内),程序将挂起。
虽然我很高兴知道我的程序似乎正在运行,但我想知道为什么需要等待,因为在我看来,我需要在杀死每个进程后等待它们,或者根本不等待。 ..
提前谢谢^^
static void backgroundExecution(char** cmd_tokens){
if(!strcmp(cmd_tokens[0], "endb")){
for(size_t i = 0; i < arraySize(PIDpool); i++){
intptr_t PID = (intptr_t) arrayGet(PIDpool, i);
kill(PID, SIGKILL);
}
wait(NULL); // <------------ THIS WAIT HERE
arrayEmpty(PIDpool);
}else{
pid_t PID = fork();
if(PID == 0){
execvp(cmd_tokens[0], cmd_tokens);
}else{
arrayPushBack(PIDpool, (void*) (unsigned long) PID);
}
}
}
So I'm working on a project for one of my programming classes, and part of this assignment is about being able to launch process in the background, and being able to kill them when the user types "endb".
In order to kill the background processes, I have an array (PIDpool) which holds the PIDs of all the processes, and whenever the user input "endb", I go through this array of PIDs and kill them one by one.
Though, in order for this to work, I had to add a single wait after I sent a kill signal to each process. If I didn't, there would be a single defunct process left, and if I put a wait for each kill signal (by putting the wait within the killing loop), the program would hang.
While I'm happy to know my program seems to be working, I'm wondering why that wait is necessary, cuz it would seem to me that I would need either to wait for each process after killing them or wait for none at all...
Thanks in advance ^^
static void backgroundExecution(char** cmd_tokens){
if(!strcmp(cmd_tokens[0], "endb")){
for(size_t i = 0; i < arraySize(PIDpool); i++){
intptr_t PID = (intptr_t) arrayGet(PIDpool, i);
kill(PID, SIGKILL);
}
wait(NULL); // <------------ THIS WAIT HERE
arrayEmpty(PIDpool);
}else{
pid_t PID = fork();
if(PID == 0){
execvp(cmd_tokens[0], cmd_tokens);
}else{
arrayPushBack(PIDpool, (void*) (unsigned long) PID);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
深入了解
wait()
和waitpid()
。等待只是等待任何子进程终止,因此它适用于您的情况。实际上,您并不检查每个进程是否确实已停止,也不检查 是否已停止
kill
函数返回错误。正如评论中指出的,您对 intptr_t 的转换不正确,不确定 PIDpool 的类型是什么,但它应该看起来像 pid_t PIDpool[POOL_SIZE];
Look deeper into
wait()
andwaitpid()
. Wait simply waits for any child process to terminate, thus it works in your case.You actually don't check whether each process has indeed stopped, nor whether the
kill
function returned an error.As pointed out in the comments, your cast to
intptr_t
is incorrect, not sure what the type ofPIDpool
is but it should look likepid_t PIDpool[POOL_SIZE];