我的任务是传递在命令行输入的整数,并通过管道从父到子传递它们,在那里整数可以加在一起并通过收割返回到父级。我的所有整数都变成了孩子中的数字4,并且sum的收获值总是以数字1的形式返回。
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
static int toChild[2];
static int toParent[2];
static int input;
static int output;
int main(int argc, char **argv)
{
pid_t pid;
int status;
int nInts = argc;
// set up pipe
pipe(toChild);
pipe(toParent);
// call fork()
pid = fork();
if (pid == 0) {
close(toChild[1]);
close(toParent[0]);
// -- running in child process --
int sum = 0;
// Receive characters from parent process via pipe
// one at a time, and count them.
// Return sum of numbers.
for (int i=1; i < nInts; i++) {
output = read(toChild[0], &input, sizeof(input));
sum += output;
}
return sum;
close(toChild[0]);
close(toParent[1]);
}
else {
close(toChild[0]);
close(toParent[1]);
// -- running in parent process --
// Send numbers (datatype: int, 4 bytes) from command line arguments
// starting with argv[1] one at a time through pipe to child process.
for (int i=1; i < nInts; i++) {
input = atoi(argv[i]);
write(toChild[1], &input, sizeof(input));
}
waitpid(pid, &status, 0);
if(WIFEXITED(status)){
// Wait for child process to return. Reap child process.
// Receive sum of numbers via the value returned when
// the child process is reaped.
printf("sum = %d\n", WIFEXITED(status));
}
close(toParent[0]);
close(toChild[1]);
return 0;
}
}
答案 0 :(得分:1)
output = read(toChild[0], &input, sizeof(input));
sum += output;
您要将read
的返回值指定给output
。这是读取的字节数,即sizeof(input)
,即平台上的4。所以你总是将sum
增加4。
你想:
ssize_t bytes_read = read(toChild[0], &input, sizeof(input));
//check that bytes_read == sizeof(input) here
sum += input;
此外:
printf("sum = %d\n", WIFEXITED(status));
WIFEXITED
只是说过程是否退出。使用WEXITSTATUS
获取退出状态。