2016-07-31 49 views
1

前我在link管:寫信給管

跨越TIMM_OSAL_WriteToFrontOfPipeTIMM_OSAL_WriteToPipe進來TIMM_OSAL_WriteToPipe的樣子,數據簡單地寫來寫管道的末端。 其中as, 在TIMM_OSAL_WriteToFrontOfPipe中,數據在寫入結束時寫入,然後再次讀取並再次寫入。

我試圖用下面的示例程序重現相同。但無法理解再次閱讀和寫作的觀點。有人能給我們一些啓示嗎?

int main(void) 
{ 
int fd[2]; 

int status = pipe (fd); 
if (status) { 
    fprintf(stderr, "** pipe create failed"); 
    return 0; 
} 

status = fork(); 
if (status < 0) 
    fprintf (stderr, "** fork failure!"); 

if (status == 0){ 
    //close (fd[1]); 
    char buf[5] = {0,}; 
    int ret_size; 
    fprintf(stderr, "child going to sleep...\n"); 
    sleep (10); 
    fprintf(stderr, "\nchild woken up...\n"); 
    ret_size = read (fd[0], buf, 5); 
    fprintf (stderr, "child printing ...\n"); 
    fprintf (stderr, "%s\n", buf); 
} else { 
    char buf[5] = {0}; 
    int read_sz; 
    int write_sz; 
    //close (fd[0]); 
    strcpy(buf,"1"); 
    write_sz = write (fd[1], buf, 1); 
    strcpy(buf,"2"); 
    write_sz = write (fd[1], buf, 1); 
    strcpy(buf,"3"); 
      write_sz = write (fd[1], buf, 1); 
    strcpy(buf,"4"); 
    write_sz = write (fd[1], buf, 1); 
    if (write_sz < 0) 
     fprintf (stderr, "write failed"); 
    else 
     fprintf(stderr, "written 1234\n"); 

    memset(buf, 0, sizeof(buf)); 

    strcpy(buf,"5"); 
    write(fd[1], buf, 1); 

    memset(buf, 0, sizeof(buf)); 

    read_sz = read (fd[0], buf, 5); 
    if (read_sz > 0) 
     fprintf(stderr, "read data :\n%s\n", buf); 

    //write back to pipe 
    write (fd[1], buf, 5); 

} 
return 0; 
} 

輸出:

written 1234 
read data : 
12345 
child going to sleep... 
child woken up... 
child printing ... 
12345 

我還沒有fork進行讀取,並在同一個進程寫試過。

回答

0

WriteToFrontOfPipe表示:

|----------------CURRENT_DATA| -> |------CURRENT_DATA YOUR_DATA|

因爲管的作用就像隊列,它需要3個操作:

|------YOUR_DATA CURRENT_DATA| //寫你的數據

|-------------------YOUR_DATA| //讀取尾巴把你的數據在前面

|------CURRENT_DATA YOUR_DATA| //保存previo我們的數據返回

+0

沒有注意到函數'writeToFrontOfPipe'中最後的大小更新!看起來很簡單,一旦你知道它。 – neeru