c - 管道 : write to front of pipe

标签 c linux pipe

我在 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/

相关文章:

python - 生成 n X n 个非同构二元矩阵的算法

c - 如何让一个线程停止另一个线程?

bash - 如何制作 ls |不那么丰富多彩?

如果文件中存在另一个字符串,Linux bash 脚本将更改一个字符串

c - 读取文件并通过管道将其发送到父进程的程序

linux - 如何在没有临时文件的情况下将一些文本附加到管道

c - 在 C 中使用 for 循环绘制图案

CLion 不会在调试中显示输出

显示系统物理 IP 的 linux 命令

regex - 我怎样才能让 sed 只匹配第一次出现的字符?