当在 C 中接收到 SIGINT 时,在进程树中使用 fork() 创建 X 个子进程

标签 c process tree fork

我已经为此苦苦挣扎了一段时间,但我放弃了,所以我寻求帮助。

我需要编写一个程序,永久等待 SIGINT (Ctrl + C),收到信号后,最后生成的进程会创建 X 个子进程。你会说它是一棵“Xary”树(如果我错了请纠正我)。

所以:

收到一次 SIGINT 时:

$ pstree -p 6227
example(6227) example(6229)
              example(6230)

收到两次时:

$ pstree -p 6227
             example(6229) example(6235)
                           example(6236)
tarea2(6227)
             example(6230) example(6234)
                           example(6237)

等等...

到目前为止,我能够捕获 SIGINT,但经过多次失败的尝试,我对如何创建树一无所知。

所以,这是我的代码: (请忽略未使用的包含)

#include <stdio.h> /* libreria estandar */
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h> 
#include <sys/types.h>
#include <sys/wait.h>

#define X 2

void reproducir(int signum)
{
 if (signum == SIGINT)
        switch(signum)
    {
        case SIGINT:
            /*SOMETHING I'VE BEEN TRYING TO FIGURE OUT*/
    }
        }
int main(void)
{
                printf("PID: %d\n", getpid()); 

    while (1)
    { 
        if (signal(SIGINT, reproducir) == SIG_ERR) 
        {
            perror("error\n");
            exit(EXIT_FAILURE);
        }
    } 
}

提前非常感谢,对于任何语法错误,我很抱歉,母语是西类牙语。

最佳答案

这就是我正在寻找的:

int reproducir(void)
{
if (spawn == 0){
for (i=0;i < X;i++)
        {
                    spawn = fork();
                    if(spawn == 0) {
                      break;
                    }
        }
    }
    return 0;
}

关于当在 C 中接收到 SIGINT 时,在进程树中使用 fork() 创建 X 个子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19085462/

相关文章:

c# - 如何从 C# 启动进程?

java - 在 Java 中打印 OO 表达式树

c++ - 从 B 树中删除一个节点

c - 指向结构的指针中的结构指针数组

c - 警告 : passing argument 1 of ‘foo’ discards ‘const’ qualifier from pointer target type

linux - 使子进程在 waitpid 之前不是僵尸进程

c - 为什么必须在rust中初始化结构?

php - 如何检查php脚本是否仍在运行

c - c中switch case中的逻辑运算符

c - 从指向无符号字符数组的指针读取位