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;
}