2017-08-12 3 views
1

Meine Aufgabe besteht darin, Integer übergeben in der Befehlszeile und übergeben sie durch eine Pipe von Eltern zu Kind, wo die ganzen Zahlen zusammen addiert und über Ernten an den Eltern zurückgegeben werden können. Alle meine ganze Zahlen drehen die Nummer 4 im Kind in, und die für die Summe erntete Wert gibt immer als die Nummer 1.Schlechte Ausgabe über ganze Zahlen von Parent zu Kind

#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

Warum rufst du 'close' nach' return' an? –

+0

Ich war besorgt, ob es früher war, bevor es die Kommunikation zu früh schließen würde. –

+0

Ich meine, diese "nahen" werden nie genannt, oder? –

Antwort

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

Sie den Rückgabewert von read-output zuweisen. Dies ist die Anzahl der gelesenen Bytes, d. H. sizeof(input), was 4 auf Ihrer Plattform ist. So Sie steigen immer sum von 4.

Sie wollen:

ssize_t bytes_read = read(toChild[0], &input, sizeof(input)); 
//check that bytes_read == sizeof(input) here 
sum += input; 

auch:

printf("sum = %d\n", WIFEXITED(status)); 

WIFEXITED nur sagt, ob der Prozess beendet. Verwenden Sie WEXITSTATUS, um den Exit-Status zu erhalten.

Verwandte Themen