gpt4 book ai didi

使用 fork() 创建 "background running" child 并用信号杀死他们中的每一个

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:55:54 25 4
gpt4 key购买 nike

我需要从同一父级创建 n 个子级,并让它们在父级无限请求信号发送给某个子级时运行。我让父级创建了那些 n 个子级,但是他们执行完了,所以我让他们进入了一个 while(1) 循环。问题是,当我试图杀死任何 child 时,它变成了一个僵尸进程,而不是真正终止它的执行。我猜那是因为 parent 仍在等待 child 终止执行并且他们不发送退出状态。所以......首先,我真的需要让 children 进入一个无限循环,让他们在 parent 要求信号时运行吗?如果我这样做,我该如何避免这个“永不终止执行”的问题?我需要找到一种方法让 children 退出那个 while 循环并发送实际的“完成执行”信号,因为我认为我不能使用 wait() 因为 children 从未真正完成运行,他们刚刚被 parent 终止。

谢谢。PS:在 Linux 中运行。这是我的代码

int main(){
int i;
pid_t parent = getpid();
pid_t pid[4];
printf("parent with pid %d\n", parent);

for(i = 0; i < 5; i++){
pid[i] = fork();
if(pid[i] < 0){
perror("Error in fork.");
exit(1);
} else if(pid[i] == 0 && getppid() == padre) {
printf("Number: %d pid %d, parent: %d\n", i, getpid(), getppid());
while(1);
}
}

if(getpid() == padre){
while(1){
printf("Enter pid and signal:\n");
int x, y;
scanf("%d", &x); // pid
scanf("%d", &y); // signal
printf("you did: kill(%d, %d)\n", x, y);
kill(x, y);
}
}
return 0;
}

编辑:实现答案的最终代码:https://github.com/sebasura/sistope

最佳答案

The problem is, when I try to kill any child, it becomes a zombie process instead of actually terminating its execution.

好吧,是的,不是。成为僵尸通常是在进程终止时发生的,直到该进程被其父进程回收为止。僵尸占用进程表中的一些空间,但它不运行,因此不消耗 CPU。

I'm guessing that's because the parent is still waiting for the children to terminate execution and they don't send the exit status.

不,这是因为 kill() 只是发送了一个信号。您需要使用 wait() 函数之一——也许是 waitpid()——来实际收集已终止的子进程。

So... First of all, do I really need to make the children enter an infinite while loop to make them be running while the parent is asking for the signals?

没有。 child 可以使用 sigwait() 或其变体之一来等待来自指定集合的​​信号,或者使用 pause() 暂停执行等待接收到任何终止信号进程或触发信号处理函数。但是请注意,有些信号在默认情况下不执行这两种操作,因此 sigwait() 可能是更好的选择。

If I do, how do I avoid this "never terminating execution" problem?

child 必须因收到信号而终止。这已经发生在你身上,因为 children 正在变成僵尸。对于您当前的代码,它可能取决于您发送的信号,但是,有些代码的默认处理不会终止进程。

关于使用 fork() 创建 "background running" child 并用信号杀死他们中的每一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43144777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com