gpt4 book ai didi

c - 管道 : write to front of pipe

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:23:50 27 4
gpt4 key购买 nike

我在 link 中遇到了 TIMM_OSAL_WriteToFrontOfPipeTIMM_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

我也尝试过不在同一进程中forking 和读写。

最佳答案

WriteToFrontOfPipe 表示:

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

因为管道就像队列一样,它需要 3 个操作:

|-------YOUR_DATA CURRENT_DATA|//写入你的数据

|--------------------YOUR_DATA|//读尾把你的数据放在前面

|------CURRENT_DATA YOUR_DATA|//保存之前的数据

关于c - 管道 : write to front of pipe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38681577/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com