【发布时间】:2017-10-20 20:52:29
【问题描述】:
我有一个任务,我需要创建一个父进程和两个具有相同父亲的子进程,第一个子进程需要读取一个字符串并在控制台打印,第二个子进程需要读取另一个字符串并打印它在控制台中,父亲需要连接这两个字符串并在控制台中打印它。这似乎很简单,但我在等待和信号部分方面遇到了困难,我不能让父亲先等待孩子的进程,这样他才能采取行动。
#include <stdlib.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
char papa[1000];
char hijo1[100];
char hijo2[100];
int main () {
pid_t son1,father;
int status;
son1 = fork();
if (son1 == 0) { //proceso hijo 1
printf("hijo1:%d\n", getpid());
fgets(hijo1, 100, stdin);
printf ("%s\n", hijo1);
sleep(2);
exit (0);
}else if (son1 > 0) { //proceso padre
pid_t son2 = fork();
if (son2 == 0) { //proceso hijo 2
printf("hijo2:%d\n", getpid());
exit (0);
}else if (son2 > 0) {
wait(NULL);
printf("padre:%d\n", getpid());
sleep(2);
exit (0);
}else {
printf("fork error");
return 0;
}
} else {
printf("fork error");
return 0;
}
return 0;
}
这只是我找到让进程父亲等待的方法时的结构
【问题讨论】: