2013-02-01 57 views
-1

我有一些東西我一直在大部分時間都在盯着,並且無法弄清楚。我正在用C編寫代碼,它應該使用管道來回傳遞一個字節,從而允許我在父進程和子進程之間切換,這將會輪流將一個字符串寫入文件。這裏是我的代碼:使用管道同步進程之間的文件寫入

#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h> 
#include <stdio.h> 
#include <stdlib.h> 
int main() 
{ 
int fd[2]; 
int fd2[2]; 
char token = 'a'; 
int file = open("output.txt", O_RDWR|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR); 
if (pipe(fd) == -1 || pipe(fd) == -1) 
{ 
    printf("Pipe failed"); 
    return(-1); 
} 
pipe(fd2); 
int pid = fork(); 
int i; 
int j; 
write(fd[1], token, 1); 
if (pid) // Parent enters here 
{ 
    for (i = 0; i < 100;) 
    { 
     if (read(fd[0], token, 1) != -1) 
     { 
      write(file, "ppppppp", 7); 
      i++; 
      write(fd2[1], token, 1); 

     } 
     //usleep(500000); 
    } 
    wait(); 
} 
else if (pid == 0) // Child enters here 
{ 
    for (j = 0; j < 100;) 
    { 
     if (read(fd2[0], token, 1) != -1) 
     { 
      write(file, "ccccc", 5); 
      j++; 
      write(fd[1], token, 1); 
     } 
     //usleep(500000); 
    } 
} 
else // Error creating child 
{ 
    exit (-1); 
}   
close(file); 
return 0; 
} 

我知道當我不使用管道寫入文件的工作,但現在我發現了一個無限循環,我不知道是什麼問題。

回答

-1

我想通了!有趣的是,小事情使得所有的差異。

+4

要麼在答案中提供解決方案,要麼刪除問題。 –

+0

我沒有看到任何新行或fflush()調用將輸出轉儲到文件.... –