1
我有一個任務,我需要創建一個父進程和2個子進程具有相同的父親,第一個子進程需要讀取一個字符串並打印它控制檯,第二個子進程需要讀取另一個字符串並將其打印在控制檯中,並且父親需要連接這兩個字符串並將其打印在控制檯中。這看起來很簡單,但即將面臨等待和信號部分的艱難時刻,我無法讓父親先等待孩子進程,以便他可以採取行動。使用等待和信號使父進程等待孩子結束
#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;
}
這僅僅是一個結構,而我發現決策過程的父親等待