2
我正在爲類應該從命令行中獲取數字的項目工作,然後將它們傳遞給子進程添加,然後父級應該收穫數字的總和。它似乎工作得很好,除非我收穫孩子的過程,它給了我大量的數字,而不是原來加在一起的數字的總和。如果我剛剛輸入0,則得到0,如果我輸入1,則得到256,依此類推。我錯過了什麼,我只是沒有正確收穫?謝謝。爲什麼我會收到大量的整數?
enter code // Numbers from command line arguments are sent to child process
// from parent process one at a time through pipe.
//
// Child process adds up numbers sent through pipe.
//
// Child process returns sum of numbers to parent process.
//
// Parent process prints sum of numbers.
static int com[2];
int main(int argc, char **argv)
{
pid_t pid;
// set up pipe
if (pipe(com))
{
printf("pipe error\n");
return -1;
}
//call fork()
pid = fork();
if (pid == 0)
{
// -- running in child process --
int sum = 0;
int input = 0;
//close output end of pipe
close(com[1]);
// Receive characters from parent process via pipe
// one at a time, and count them.
for (int idx = 1; idx < argc; idx++) //stared idx at 1 instead of 0
{
read(com[0], &input, 4); //changed from 4
sum = sum + input;
}
printf("child sum: %i \n", sum); // error checking
// Return sum of numbers.
return sum;
}
else {
// -- running in parent process --
int sum;
//close output end of pipe
close(com[0]);
// 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 idx = 1; idx < argc; idx++)
{
int output = 0;
output = atoi(argv[idx]);
write(com[1], &output, 4);
printf("output: %i \n", output);// error checking
}
close(com[1]);
// Wait for child process to return. Reap child process.
// Receive sum of numbers via the value returned when
// the child process is reaped.
waitpid(pid, &sum, 0);
printf("sum = %d\n", sum);
return 0;
}
}
這裏
好像它在我的移位位進行檢查。 – ShiggityMiggity
退出狀態存儲在退出狀態的高位8位,有效地將您的總和乘以256.您的總和也限制爲255. –
您最好閱讀子進程的標準輸出。首先是測試更容易,它允許您接受超過256的總和。命令返回的* status *僅用於狀態:將其用於錯誤條件,但將stdout用於有意義的數據。 –