2013-05-05 97 views
0

我想叉兩個孩子。父母讀取發送到管道的行。孩子讀它並將其寫入另一個管道,最後child2讀取它。但是,輸出始終是父項。謝謝!C叉兩個孩子和父母與子女之間的管道

#define MAX 80 

void child(); 
void parent(); 
void childtwo(); 
char * getli(); 
void printline(char *buffer, int count); 
char * convertCase(char *str); 

int pipe1[2]; 
int pipe2[2]; 
int main(int argc, char **argv) 
{ 
    pipe(pipe1); 
    pipe(pipe2); 
    if(fork()){ 
    if(fork()){ 
     printf("1st\n"); 
     parent(); 
      exit(0); 
    } 
    else{ 
     printf("3rd\n"); 
     childtwo(); 
     exit(0); 
    } 
    } 
    else{ 
    printf("2nd\n"); 
    child(); 
    exit(0); 
    } 
} 

void child(){ 
    char *buf; 
    int count = 0; 
    close(pipe1[1]); 
    close(pipe2[0]); 
    while(1){ 
    buf = (char *) malloc(sizeof(char)*MAX); 
    read(pipe1[0], buf, MAX); 
    if (strcmp(buf,"quit")== 0){ 
    printf("Child is leaving\n"); 
    free(buf); 
    break; 
    } 
    else{ 
    printf("Child: "); 
    printline(buf,strlen(buf)); 
    write(pipe2[1],buf, strlen(buf)+1); 
    free(buf); 
     } 
    close(pipe2[1]); 
    close(pipe1[0]); 
    exit(0); 
    } 
} 

void childtwo() 
{ 
    char *buf; 
    int count = 0; 
    close(pipe2[1]); 
    buf = (char *) malloc(sizeof(char)*MAX); 
    while(1){ 
    buf = (char *) malloc(sizeof(char)*MAX); 
    read(pipe2[0], buf, MAX); 
    if (strcmp(buf,"quit")== 0){ 
     printf("Childtwo is leaving\n"); 
     free(buf); 
     break; 
    } 
    else{ 
     printf("Childtwo:"); 
     printline(buf,strlen(buf)); 
     free(buf); 
    } 
    } 
    close(pipe2[0]); 
    exit(0); 
} 

void parent(){ 
    char * buffer; 
    int count = 0, done=0; 
    close(pipe1[0]); 
    while (done != 1){ 
    printf("parent getting line: "); 
    buffer = getli(); 
    write(pipe1[1],buffer, strlen(buffer)+1); 
    if (strcmp(buffer,"quit")== 0){ 
     puts("parent goes away"); 
     free(buffer); 
     break; 
    } 
    free(buffer); 
    } 
    close(pipe1[1]); 
    exit(0); 
} 
+0

你的子進程有內存泄漏,你在循環之前和循環內部分配'buf' _both_。 – 2013-05-05 00:48:45

+0

謝謝指出!但刪除它並沒有解決問題 – otchkcom 2013-05-05 00:52:38

+0

你是否檢查過所有系統調用實際上是_work_?您應該檢查他們返回的內容,例如, 'read'返回'-1',那麼出現了一些錯誤,你可以使用例如['perror'](http://en.cppreference.com/w/c/io/perror)打印出錯誤。您應該爲_all_函數執行此操作,即使'fork'可能會失敗。 – 2013-05-05 01:07:43

回答

0

我的猜測是,它適用於第一行,但不適用於任何其他。

這是因爲第一個子進程(在child函數中)在讀取其輸入後退出。您可能打算將closeexit調用放在循環之外。

+0

不幸的是,它甚至不是第一次工作。我關閉並退出循環外,但得到了相同的結果 – otchkcom 2013-05-05 00:56:27