linux系统编程之pipe

序言

系统调用pipe用于创建匿名管道(不反应在文件系统的管道)

pipe创建的管道只适用于父子进程间通信(因为fd[2])

代码

#include <unistd.h>
#include <sys/wait.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUF_SIZE 4096

#define DEBUG_MSG(msg) do{ \
    fprintf(stdout,"[file:%s],[function:%s],[line:%d],%s\n",__FILE__,__FUNCTION__,__LINE__,msg); \
}while(0);

int main(int argc, char *argv[])    
{
    int fd[2];  //管道的两个文件描述符,0为读,1为写
    char buf[BUF_SIZE];
    ssize_t num_read;

    if (argc != 2 || 0 == strcmp(argv[1], "--help"))
    {
        fprintf(stderr, "%s string\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    // 创建管道
    if (-1 == pipe(fd))
    {
        perror("pipe error");
        exit(EXIT_FAILURE);
    }
    switch (fork())
    {
        case -1:
            DEBUG_MSG("fork error");
            break;
        // 子进程
        case 0:
            // 关闭写端
            if (-1 == close(fd[1]))
            {
                DEBUG_MSG("child close 1 error");
            } 
            for (;;)
            {
                // 从管道读取数据
                if (-1 == (num_read = read(fd[0], buf, BUF_SIZE)))
                {
                    DEBUG_MSG("child read error");
                }
                if (0 == num_read)
                {
                    break;
                }
                // 将读取的数据输出到终端
                if (write(STDOUT_FILENO, buf, num_read) != num_read)
                {
                    DEBUG_MSG("child write error");
                }  
            }
            write(STDOUT_FILENO, "\n", 1);
            fprintf(stdout,"child process[%d]read from pipe\n",getpid());
            (void)fflush(NULL);
            // 关闭读端
            if (-1 == close(fd[0]))
            {
                DEBUG_MSG("child close 0 error");
            }
            exit(EXIT_SUCCESS);
            //break;
        // 父进程
        default:
            // 关闭读端
            if (-1 == close(fd[0]))
            {
                DEBUG_MSG("parent close 0 error");
            }
            // 将命令行指定内容写到管道
            fprintf(stdout,"parent process[%d]write to pipe\n",getpid());
            if (write(fd[1], argv[1], strlen(argv[1])) != strlen(argv[1]))
            {
                DEBUG_MSG("parent write error");
            }
            // 关闭写端
            if (-1 == close(fd[1]))
            {
                DEBUG_MSG("parent close 1 error");
            }
            // 等待子进程结束
            wait(NULL);
            exit(EXIT_SUCCESS);
            //break;
    }
}

现象

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值