linux操作系统编程——简单的pipe管道

程序要求:

     子进程读,父进程写,由pipe管道来实现进程间的通信

程序如下:

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

static void child_read(int *);
static void father_write(int *, int );

int main(int argc, const char *argv[])
{
    pid_t pid;
    int pipe_fd[2];

    if (pipe(pipe_fd) < 0)                //创建pipe管道
    {
        perror("failed to create pipe");
        exit(-1);
    }

    if ((pid = fork()) < 0)
    {
        perror("failed to fork pid");
        exit(-1);
    }

    if (pid == 0)
        child_read(pipe_fd);     //子进程负责读数据
    else
        father_write(pipe_fd, pid);     //父进程负责写数据

    return 0;
}

static void child_read(int *pipe_fd)
{
    char buf[100];

    close(pipe_fd[1]);    //子进程负责读数据,因此关闭写端

    while (read(pipe_fd[0], buf, sizeof(buf)) > 0)     //读数据
     {
        if (strncmp(buf, "quit", 4) == 0)
            exit(0);

        printf("read : %s\n", buf);
        memset(buf, sizeof(buf), 0);
    }

    return ;
}

static void father_write(int *pipe_fd, int pid)
{
    char buf[100];

    close(pipe_fd[0]);    //同理,关闭读端

    while (1)
    {
        usleep(500);
        printf(">");
        fgets(buf, sizeof(buf), stdin);
        buf[strlen(buf) - 1] = 0;

        write(pipe_fd[1], buf, strlen(buf) + 1);   //写数据

        if (strncmp(buf, "quit", 4) == 0)
            break;
            
        memset(buf, sizeof(buf), 0);
    }

    waitpid(pid, NULL, 0);

    return ;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值