我在link
中遇到TIMM_OSAL_WriteToFrontOfPipe
和TIMM_OSAL_WriteToPipe
在TIMM_OSAL_WriteToPipe
看起来,数据只是写入管道末端。
在哪里,
在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 :(得分:0)
WriteToFrontOfPipe表示:
|----------------CURRENT_DATA| -> |------CURRENT_DATA YOUR_DATA|
因为管道就像队列一样,需要3次操作:
|------YOUR_DATA CURRENT_DATA|
//编写您的数据
|-------------------YOUR_DATA|
//读尾以将数据放在前面
|------CURRENT_DATA YOUR_DATA|
//保存以前的数据