0
当我在gdb中运行时,父进程在waitpid处挂起,我不知道为什么。父母应该从argv获取参数并通过管道将其发送给孩子。然后,父母应该通过返回来接收来自孩子的参数的总和。不知道为什么它这样做。父进程在调用waitpid后挂起
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/poll.h>
static int myPipe[2];
int main(int argc, char **argv)
{
pid_t pid;
int value;
int status;
// set up pipe
if(pipe(myPipe))
{
printf("pipe error\n");
return -1;
}
// call fork()
printf("CS201 - Assignment 3 Premium - I. Forgot\n");
pid = fork();
if (pid == 0) {
// -- running in child process --
int sum = 0;
close(myPipe[1]);
for(int i = argc; i > 1; i--)
{
read(myPipe[0], &value, sizeof(value));
sum += value;
}
// Return sum of numbers.
return sum;
}
else {
// -- running in parent process --
int sum = 0;
close(myPipe[0]);
for(int i = argc; i > 1; i--)
{
value = atoi(argv[i-1]);
write(myPipe[0], &value, sizeof(value));
}
waitpid(pid, &status, 0);
sum = status;
printf("sum = %d\n", sum);
return 0;
}