我正在编写一个程序,它接受来自用户的两个整数值作为输入,X和Y(它用于赋值)。
棘手的部分是程序必须创建父和子,其中父进程将读取X并且子进程将读取Y(使用scanf
)。
该计划的预期产出如下:
From parent 2255: child with PID 2256 is created
From parent 2255: Reading X from the user
>> 99
>> X in parent is 99
From child: Reading Y from the user
>> 88
>> Y in child is 88
我遇到的问题是孩子自动执行,并且不会等到父母收到输入。
我的教授暗示我们可以在子进程开始时使用sleep()来解决这个问题,但我没有运气。
我的示例代码(无效):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h> // pid_t
#include <unistd.h> // NULL, fork()
#include <errno.h> // errno
int main(void){
// Initializing variables
int X = 0, Y = 0;
// Fork
pid_t pid;
pid = fork();
// ERROR
if (pid < 0){
// error handling
}
// PARENT
else if (pid > 0){
// Read X
printf("From parent %d: Reading X from the user\n>> ", pid);
scanf(" %d", &X);
printf("X in parent is %d\n", X);
// Some other code afterwards
}
// CHILD
else {
// Read Y
printf("From child: Reading Y from the user\n>> ");
scanf(" %d", &Y);
printf("Y in child is %d\n", Y);
// Some other code afterwards
}
return 0;
}
我真的很感激任何帮助。谢谢!
答案 0 :(得分:0)
父母可以等待孩子完成,其中包括以下几行
printf("X in parent is %d\n", X);
int status = 0;
waitpid(pid, &status, 0);
// Some other code afterwards
副作用是//之后的其他一些代码只会在孩子退出后执行。
如果需要同步两个过程来读取X&amp; Y然后做计算然后考虑使用条件变量(等待/信号)。像父母一样的东西等待由孩子设定的条件,以便父母可以继续前进。 waitpid仍然可能是一个好主意,除非您不关心创建僵尸进程(即父级退出而没有获得其子级的状态)或正确设置SIGCHLD。