【发布时间】:2014-11-24 20:13:20
【问题描述】:
在 C 语言中创建一个程序,该程序创建两个进程并通过管道连接它们。
第一个后代将其标准输出重定向到管道中,并将随机数对(空格分隔)写入其中(函数 rand)。将数字的输出延迟 1 秒。
第二个后代将管道输出重定向到它的标准输入,将它的标准输出重定向到当前目录中名为 out.txt 的文件中。
父进程等待 5 秒,然后将 SIGUSR1 发送给第一个进程(数字生成器)。这应该正确终止两个进程。它等待子进程终止(等待函数)并自行终止。
我真的需要帮助: 第一个后代必须处理 SIGUSR1 信号(sigaction 函数),如果收到这样的信号,它会在它的标准错误中打印一个字符串“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);
}
【问题讨论】:
-
如果这是 C,为什么要标记 C++? (C != C++ 用于许多“本机”解决方案)