1
跨越TIMM_OSAL_WriteToFrontOfPipe
和TIMM_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
進行讀取,並在同一個進程寫試過。
沒有注意到函數'writeToFrontOfPipe'中最後的大小更新!看起來很簡單,一旦你知道它。 – neeru