我已经为此苦苦挣扎了一段时间,但我放弃了,所以我寻求帮助。
我需要编写一个程序,永久等待 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/