2012-04-26 22 views
0

通信過程中,我通過線閱讀以下文件(file.txt的)線:與其他兩個過程

1 
    -5 
    6 
    -8 
    -33 
    21 

父親發送負數到一個過程,並且發送正數到第二個過程:

#include <stdio.h> 
#include <unistd.h> 
#include <stdlib.h> 
#include <sys/wait.h> 

void Fils1(int *tube1) 
{ 
    int n; 
    int cpt = 0; 
    close (tube1[1]); 

    while (read (tube1[0], &n, 1) >0) 
    { 
    cpt+=n; 
    } 

    printf("Son 1, count : %i \n", cpt); 
    exit (1) ; 
} 

void Fils2(int *tube2) 
{ 
    int n; 
    int cpt = 0; 
    close (tube2[1]); 

    while (read (tube2[0], &n, 1) >0) 
    { 
    cpt+=n; 
    } 

    printf("Son 2, count : %i \n", cpt); 
    exit (1) ; 
} 


int main(int argc, char *argv[]) 
{ 
FILE* file; 
int n; 

file = fopen (argv[1], "r"); 

if (file == NULL){ 
     printf("Error open file %s\n", argv[1]); 
     exit(1); 
    } 

int tube1[2]; 
int tube2[2]; 


if (pipe(tube1) != 0) 
{ 
    fprintf(stderr, "Error tube 1\n"); 
    return EXIT_FAILURE; 
} 


if (pipe(tube2) != 0) 
{ 
    fprintf(stderr, "Error tube 2\n"); 
    return EXIT_FAILURE; 
} 

int pid1 = fork(); 

if(pid1 == 0) 
{ 
    printf("Creation of the first son ! \n"); 
    Fils1 (tube1); 
} 
else 
{ 
    int pid2 = fork(); 
    if(pid2 == 0) 
    { 
     printf("Creation of the second son ! \n"); 
     Fils2 (tube2); 
    } 
    else 
    { 
     printf("I'm the father! \n"); 

     close (tube1[0]); 
     close (tube2[0]); 

     while (!feof(file)) 
     { 
     fscanf (file,"%d",&n); 
     if (n>0) 
     { 
      write (tube1[1], &n, 1); 
     } 
     else 
     { 
      write (tube2[1], &n, 1); 
     } 
     } 
     fclose (file); 

     if(wait(NULL) == -1) 
     { 
     printf("Error wait()\n"); 
     exit(1); 
     } 
    } 
} 

return EXIT_SUCCESS; 
} 

每個兒子都在計數,並將其顯示在屏幕上。

當我執行,我只有說:

I'm the father! 
Creation of the first son! 
Creation of the second son! 

當我也希望

Son1, count : 28 
    Son2, count : 46 
+1

好的,什麼是你期待它會發生?你想做什麼? – karlphillip 2012-04-26 16:22:53

+0

預期的結果: Son1,count:28 Son2,count:46 – ilias 2012-04-26 16:29:09

+1

備註:您正在讀'寫'錯誤。大小不應該是1,但'sizeof n' – 2012-04-26 16:34:26

回答

3

的問題是你不關管道,你應該。

  • Child1應該關閉tube2(兩端)
  • CHILD2應該關閉tube1(兩端);
  • 家長應關閉寫入結束(後while
+0

它工作:)! 非常感謝! – ilias 2012-04-26 16:49:43