gpt4 book ai didi

c - SIGUSR1 - 杀死 C 中的 sigaction

转载 作者:行者123 更新时间:2023-11-30 17:25:08 25 4
gpt4 key购买 nike

用 C 语言创建一个程序,该程序创建两个进程并通过管道连接它们。

第一个后代将其标准输出重定向到管道中,并将(空格分隔的)随机数对写入其中(函数 rand)。将数字的输出延迟 1 秒。

第二个后代将管道输出重定向到它的标准输入,将它的标准输出重定向到当前目录中名为 out.txt 的文件。

父进程等待 5 秒,然后向第一个进程(数字生成器)发送 SIGUSR1。这应该正确终止两个进程。它等待子进程终止(等待函数)并自行终止。

我确实需要帮助:第一个后代必须处理 SIGUSR1 信号(sigaction 函数),并且在接收到此类信号的情况下,它会向其 stderr 打印字符串“TERMINATED”并终止。

FILE *file;
file = fopen(NAZEV, "a+");

int pipefd[2];
pipe(pipefd);

pid_t pid1;
int retcode;
pid1=fork();
if(pid1 == 0) // child 1
{
close(roura[0]);
printf("child1...\n");
dup2(roura[1], STDOUT_FILENO);

int i = 0;

while(i < 6)
{
i++;
int a = rand();
int b = rand();
sleep(1);
printf("%d %d\n", a, b);
}
close(roura[1]);
exit(45);


}
else if (pid1 < 0)
{
printf("Fork selhal\n");
exit(2);
}
else
{
pid_t pid2;
pid2 = fork();
if (pid2 == 0) //child 2
{
close(roura[1]);
dup2(roura[0], STDIN_FILENO);

printf("child2...\n");
int i = 0;
while(i < 5)
{
i++;
int c;
int d;
scanf("%d %d", &c, &d);
printf("%d %d\n", c, d);
fprintf(file,"%d %d\n", c, d);
}

printf("child2 end\n");
exit(0);
}
else if (pid2 < 0)
{
printf("Fork error\n");
exit(2);
}else
{
sleep(5);
kill(pid1, SIGUSR1);
wait(&pid1); //wait for child 1
wait(&pid2); //wait for child 2
printf("parent end\n");
exit(0);
}
}
exit(0);

}

最佳答案

向 sigusr1 添加信号处理程序,打印到 stderr 并退出。试试这个,适合在cygwin中编译:

    #include <stdio.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#ifndef STDIN_FILENO
# define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
# define STDOUT_FILENO 1
#endif

void sig_handler(){
fprintf(stderr,"TERMINATED");
exit(0);
}

void main(int argc, char ** argv){
FILE *file;
file = fopen("NAZEV", "a+");

int pipefd[2];
int roura[2] ;
pipe(pipefd);

pid_t pid1;
int retcode;
pid1=fork();
if(pid1 == 0) // child 1
{
close(roura[0]);
printf("child1...\n");
dup2(roura[1], STDOUT_FILENO);
if (signal(SIGUSR1, sig_handler) == SIG_ERR){
printf("\ncan't catch SIGUSR1\n");
exit(13);
}
int i = 0;

while(i < 6)
{
i++;
int a = rand();
int b = rand();
sleep(1);
printf("%d %d\n", a, b);
}
close(roura[1]);
exit(45);


}
else if (pid1 < 0)
{
printf("Fork selhal\n");
exit(2);
}
else
{
pid_t pid2;
pid2 = fork();
if (pid2 == 0) //child 2
{
close(roura[1]);
dup2(roura[0], STDIN_FILENO);

printf("child2...\n");
int i = 0;
while(i < 5)
{
i++;
int c;
int d;
scanf("%d %d", &c, &d);
printf("%d %d\n", c, d);
fprintf(file,"%d %d\n", c, d);
}

printf("child2 end\n");
exit(0);
}
else if (pid2 < 0)
{
printf("Fork error\n");
exit(2);
}else
{
sleep(5);
kill(pid1, SIGUSR1);
wait(&pid1); //wait for child 1
wait(&pid2); //wait for child 2
printf("parent end\n");
exit(0);
}
}
exit(0);
}

关于c - SIGUSR1 - 杀死 C 中的 sigaction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27113347/

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