2017-08-12 258 views
1

我的任務是傳遞在命令行中輸入的整數,並將它們通過從父母到孩子的管道傳遞,整數可以加在一起並通過收穫返回給父母。我所有的整數變成在孩子4號,以及總和收穫價值總是返回爲數字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; 
     } 
} 
+1

你爲什麼在返回後調用'close'? –

+0

我很擔心它是否會在太早關閉通訊之前。 –

+0

我的意思是那些'close'永遠不會被調用,不是嗎? –

回答

1
output = read(toChild[0], &input, sizeof(input)); 
sum += output; 

您的read的返回值分配給output。這是讀取的字節數,即sizeof(input),在您的平臺上是4。所以,你總是由4

增加sum你想:

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獲取退出狀態。

相關問題