gpt4 book ai didi

c - 如何 fork 一个 child 来替换已完成的 child ?

转载 作者:行者123 更新时间:2023-11-30 15:42:11 26 4
gpt4 key购买 nike

我正在编写一个程序,我在其中 fork 了 n 个 child 。在某些时候,我通过管道将 ID 发送给父级,父级应该重生该子级。

int main()
{
i = 0;
n = 5;

pid_t* pids = malloc(n * sizeof(pid_t));

pid_t child;
while ((i < n) && (child = fork()) > 0)
{
pids[i] = child;
++i;
}

if (child > 0) //parent
{
//I read the ID of a child to be reforked from a pipe
}
else
if (child == 0) //child
{
//Send ID to the pipe
}
else //error
{
}

return 0;
}

我尝试使用 child = fork() 简单地在父级中重新 fork 子级,但这显然不是解决方案。

编辑

我将 pid 存储在数组中,并与信号量保护的管道进行通信。如果我收到一个数组编号,我应该用一个新的替换那个死去的 child 。

我正在尝试发布最少的代码:

    i = 0;
n = 5;

pid_t* pids = malloc(n * sizeof(pid_t));

pid_t child;
while (i < n)
{
child = fork();

if (child == 0)
{

}
else
if (child < 0)
{
for (;;)
{
//If I finish my work
//I send my number in the pids array (0,1,..)
return;
}
return;
}

pids[i] = child;
++i;
}

for (;;)
{
//parent
//...I read the ID of a child to be reforked from a pipe
child = fork(); //pids[?] = ...
//...
}

最佳答案

你几乎已经拥有它了。只需将代码再拆分一点就可以了。

pid_t child;
while (i < n)
{
child = fork();

if (child == 0)
{
child_code();
exit(0);
}
else if (child < 0)
{
//error handling
}
pids[i] = child; // will be -1 if error occured
++i;
}
// parent code

关于c - 如何 fork 一个 child 来替换已完成的 child ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20289878/

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