Linux 无名管道使用示例

/**
 * @file pipe_no_name.c
 * @author your name (you@domain.com)
 * @brief 无名管道
 * 无名管道用于具有亲缘关系的进程间通信
 * @version 0.1
 * @date 2021-11-20
 * 
 * @copyright Copyright (c) 2021
 * 
 */
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <wait.h>

int main()
{
    int ret;
    int pipefd[2] = {0};
    char buffer[64] = {0};
    //创建无名管道
    ret = pipe(pipefd);
    if (ret == -1)
    {
        perror("pipe");
        return -1;      
    }

    //创建子线程
    pid_t pid = fork();
    if (pid == -1)
    {
        perror("fork");
        return -1;
    }

    if (pid == 0)
    {
        //child
        close(pipefd[1]);
        int n;

        //将管道中的小说读出  写入文件中
        FILE *mortal_fs = fopen("mortal_copy.txt", "w+");
        if (mortal_fs == NULL)
        {
            perror("fopen");
            return -1;
        }
        while ((n = read(pipefd[0], buffer, sizeof(buffer))) != 0)
        {
            fwrite(buffer, 1, n, mortal_fs);
            //fflush(mortal_fs);
            //sleep(2);
        }
        fclose(mortal_fs);
        close(pipefd[0]);
    }
    else
    {
        //parent
        close(pipefd[0]);
        int n;

        //打开小说文件 把内容写到管道中
        FILE *mortal_fs = fopen("mortal.txt", "r");
        if (mortal_fs == NULL)
        {
            perror("fopen");
            return -1;
        }
        while ((n = fread(buffer, 1, sizeof(buffer), mortal_fs)) != 0)
        {
            write(pipefd[1], buffer, n);
        }
        if (ferror(mortal_fs))
        {
            printf("fread fail\n");
            return -1;
        }
        fclose(mortal_fs);
        close(pipefd[1]);

        wait(NULL);
    }
}


示例代码如上,父进程向管道写入数据,子进程从管道中读出数据并保存到文件中。无名管道一般只用于父子进程或兄弟进程(具有亲缘关系)之间通信。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值