linux进程间的通信之管道

1.父子进程间使用匿名管道

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<string.h>
int main()
{
    int fds[2];//创建管道描述符
    int r=pipe(fds);//创建匿名管道
    if(r==-1)printf("创建匿名管道失败:%m\n"),exit(-1);
    printf("创建匿名管道成功\n");
    if(fork())
    {
        //父进程写入数据
        char buff[1024];
        while(1)
        {
            scanf("%s",buff);
            write(fds[1],buff,strlen(buff));
        }
    }
    else
    {
        char buff[1024];
        int r;
        while(1)
        {
            r=read(fds[0],buff,1023);
            if(r>0)
            {
                buff[r]=0;//结束符号
                printf(">>%s",buff);
            }
        }
    }
close(fds[0]);
close(fds[1]);
    
return 0;
    
}

2.非父子进程间通信

进程A负责写入数据

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
int main()
{
    int r=mkfifo("mkfifo..dat",0666);
    if(r==-1)printf("创建管道文件失败:%m\n"),exit(-1);
    printf("创建管道文件成功");
    int fd=open("mkfifo.dat",O_WRONLY);
    if(fd==-1)printf("打开管道文件失败:%m\n"),unlink("mkfifo.dat"),exit(-1);
    printf("打开管道文件成功");
    char buff[1024];
    while(1)
    {
        scanf("%s",buff);
        write(fd,buff,strlen(buff));
    }
close(fd);
unlink("mkfifo.dat");//删除管道文件

return 0;
}

进程B负责读数据

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
int main()
{
    
    int fd=open("mkfifo.dat",O_RDONLY);
    if(fd==-1)printf("打开管道文件失败:%m\n"),unlink("mkfifo.dat"),exit(-1);
    printf("打开管道文件成功");
    char buff[1024];
    while(1)
    {
        int r=read(fd,buff,1023);
        if(r>0)
        {
            buff[r]=0;
            printf(">>%s",buff);
        }
    }
close(fd);


return 0;
}

注意:
        1. 如果你使用的是虚拟机,并且使用共享文件夹,在工作目录下是无法创建管道文件的,可以将两个源码拷贝到~目录下执行。
        2. 打开管道文件的时候只有两边一起打开才会返回,只有一边打开会阻塞。
        3. 先关闭读取端,会导致写入端进程结束;先关闭写入端,不对读取端造成影响。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值