【发布时间】:2021-04-25 07:45:43
【问题描述】:
目标是父进程应该生成一个子进程,父进程打印 1 到 100 之间的偶数,子进程打印奇数。这种机制应该使用信号来实现(数字应该是按顺序排列的,例如 parent:0、child:1、parent:2...)我编写了以下代码:
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<signal.h>
#include<sys/wait.h>
int main(){
pid_t pid;
pid = fork();
if (pid == -1){
return 1;
}
if (pid == 0){
for(int i=0; i<=100; i++){
if (i % 2 != 0){
printf("I am the child: %d\n", i);
}
}
} else {
kill(pid, SIGSTOP);
for(int i=0; i<=100; i++){
if(i % 2 == 0){
printf("I am the parent: %d\n", i);
kill(pid, SIGCONT);
}
}
wait(NULL);
}
return 0;
}
但是输出的顺序不是应该的,父母先打印他所有的数字,孩子跟着他。我想知道 SIGSTOP 和 SIGCONT 是否不是适合使用的信号,但没有其他合乎逻辑的解决方案。
任何建议都会有所帮助。谢谢。
【问题讨论】:
-
父项中没有代码等待子项进行打印。建议使用
sigwait和SUGUSR信号。请参阅上面的重复帖子。
标签: c unix process signals fork