linux 进程间通信:匿名管道pipe()

进程间内存独立且相互不可见,进程间通信需要特殊方法

匿名管道pipe()

/* Create a one-way communication channel (pipe).
   If successful, two file descriptors are stored in PIPEDES;
   bytes written on PIPEDES[1] can be read from PIPEDES[0].
   Returns 0 if successful, -1 if not.  */
extern int pipe (int __pipedes[2]) __THROW __wur;
输入一个2个元素的int数组地址,生成单向匿名管道,调用后该数组[0]为读取描述符,[1]为写入描述符,默认打开,使用前需要关闭另一通道,然后直接调用系统调用函数write open来进行读写

 

一个实例

#include "sys/wait.h"//waitpid声明处
#include "sys/types.h"//pid_t声明处,实质是int
#include "stdio.h"
#include "unistd.h"//系统调用函数声明 fork,close,write read pipe等
#include "stdlib.h"
#include "string.h"


int main(int argc, char const *argv[])
{
    int p[2];
    pipe(p);//两个文件描述符已经打开
    pid_t cpid = fork();

    if(cpid == 0)
    {
        char buf[11] = {0};
        close(p[1]);//关闭写管道

        read(p[0], buf, 10); //从读管道中读取一次,最多读取10字节
        printf("child process read: %s\n",buf);
        printf("child process end\n");
        exit(0);//打印出来,退出

    }
    else if(cpid > 0)
    {
        close(p[0]);//关闭读管道
        char buf2[100] = {0};
        scanf("%s", buf2);//从标准输入读取一段数据
        write(p[1], buf2, strlen(buf2));//通过管道发送到子进程
        waitpid(cpid, NULL, 0);//等待子进程结束
        printf("parent process end\n");
    }
    

    /* code */
    return 0;
}

 运行,分别输入10字节以上和10字节以下的数据看看

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值