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

标签 c fork system-calls

我正在编写一个程序,我在其中 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/

相关文章:

C printf 浮点四舍五入

android - For IOS 中的 C++ 网络库

c - 使用 fork() 时,getline() 重复读取文件

linux - Linux内核中的系统调用是如何定义的? compat_sys_xxx 和 sys_xxx 之间有什么关系?

c++ - 发送 URL 时 chrome 中的奇怪字符

python - 在缓慢的系统调用中处理 SIGINT

c - C 中的 AVR - 将寄存器的值存储在变量中

c - 嵌套结构语法

linux - 在 Linux 中立即检测新进程的创建

c++ - 使用 shmat 和 shmget 与 forks 相乘矩阵