进程间通信-管道通信-无名管道(pipe)

无名管道:

        Linux中 inode 用于唯一标识一个文件,而无名管道(pipe)在系统中是没有名字的,也就是没有(inode),它的内容直接保存在操作系统的内核中。

        无名管道可以通过系统 API 提供的 IO 函数进行操作,但是不能使用 open/close 函数进行打开或者关闭。

        无名管道使用 read/write 进行读写,但是 使用 read/write 必须得有一个文件描述符。所以,使用无名管道 pipe 时,就必须先创建 文件描述符。

文件描述符的创建:

#include <unistd.h>

int pipe(int pipefd[2]);
参数:
    @pipefd[0]:    保存 read 文件描述符
    @pipefd[1]:    保存 write 文件描述符
返回值:
    成功返回 0
    失败返回 -1,并设置错误码 errno

pipe 无名管道的特点:

        1.pipe 有两端,一端用来读取数据,一端用来写入数据

        2.按顺序读取,不能使用 lseek

        3.内容读取完毕,管道中就没有数据了

        4.pipe 随内核持续性

无名管道的操作流程

        1.创建文件描述符

        2.创建子进程

        3.在子进程中写入数据

        4.在父进程中读取数据

        5.关闭无名管道

代码实现:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>

#define N 30
int main()
{
    //  1、先创建一个无名管道
    int pipefd[2];
    if(pipe(pipefd) == -1)
    {
        perror("pipe error");
        exit(-1);
    }
    //  2、创建新进程进行通信   子进程写入管道数据,父进程读取
    char buf[N] = { 0};      //  保存数据
    if(fork() == 0)         //  子进程
    {
        while(1)
        {
            scanf("%s",buf);        //  不能获取空白字符
            write(pipefd[1],buf,N);
            if(strcmp(buf,"over") == 0) //  输入 over 结束
            {
                printf("CHILD OVER\n");
                exit(0);
            }
        }      
    }
    else
    {
        while(1)
        {
            read(pipefd[0],buf,N);
            printf("CHILD SEND %s\n",buf);
            if(strcmp(buf,"over") == 0) //  输入 over 结束
            {
                printf("PAPA OVER\n");
                wait(NULL);
                break;
            }
        }
    }

    //  3、关闭无名管道
    close(pipefd[0]);
    close(pipefd[1]);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值