viewimage.php?id=2ab4c42ef0d0&no=24b0d769e1d32ca73cec81fa11d02831ce3cef1b9542c00ceb084720fba3823a75e872cdd9f8473bc34da1df5a38b6ff1beebf5d40e6d1181610ec0c05b64d9df1


#include <errno.h>

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>


#define LINEWIDTH 128


int main(int argc, char *argv[])

{

  int nread;

  char buf[LINEWIDTH];

  int fds[2][2];

  int pid[2];

  int i, j, err;

  long x, sum = 0;


  for (i = 0; i < 2; i++) {

    if ((err = pipe(fds[i])) < 0)

      exit(1);

    pid[i] = fork();

    if (pid[i] == 0) {

      close(fds[i][1]);

      j = i;

      goto children;

    }

  }

  for(i = 0; i < 2; i++)

    close(fds[i][0]);


  while(1) {

    memset(buf, 0, 128);

    if ((nread = read(STDIN_FILENO, &buf, LINEWIDTH)) > 0) {

      if(nread < 2)

        continue;

      if(buf[0] == '-'){

        close(fds[i][1]);

        exit(0);

      }

      errno = 0;

      long x = strtol(buf, NULL, 10);

      if (errno)

        continue;

      write(fds[x%2][1], &x, sizeof(long));

    } else {

      for(i=0; i<2; i++)

        close(fds[i][1]);

      }

    }

    exit(0);

children:

  while(1){

    if((nread = read(fds[j][0], &x, sizeof(long))) == sizeof(long)){

      sum += x;

    } else {

      printf("sum of %s integers: %ld ", j ? "odd": "even", sum); exit(0);

    }

  }

}


해석은 질문자의 몫으로 남겨둠


1 2 3 4 5 6 7 8 9 -1 sum of odd integers: 25 sum of even integers: 20