Linux系统编程:(6)、进程间的通信之有名管道

//管道文件写端代码

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
int main()
{
    int ret = mkfifo("./myfifo",0666);
    if(ret == -1)
    {
        perror("mkfifo failed:\n");
        exit(0);
    }

    int fd = open("./myfifo",O_WRONLY);
    if(fd == -1)
    {
        perror("open fifo failed:\n");
        exit(0);
    }

    int i;
    for(i = 0; i < 3;i++)
    {
        int ret1 = fork();
        if(ret1 == -1)
        {
            perror("fork failed:\n");
            exit(0);
        }
        if(ret1 == 0)
            break;
        else
            continue;
    }

    if(i == 0)
    {
        char *a = "abc";
        int ret2 =  write(fd,a,strlen(a));
        if(ret2 == -1)
        {
            perror("write a failed:\n");
            exit(0);
        }
        close(fd);
    }

    if(i == 1)
    {
        char *b = "123";
        int ret3 =  write(fd,b,strlen(b));
        if(ret3 == -1)
        {
            perror("write  b failed:\n");
            exit(0);
        }
        close(fd);

    }

    if(i == 2)
    {
        char *c = "hhh";
        int ret4 =  write(fd,c,strlen(c));
        if(ret4 == -1)
        {
            perror("write c failed:\n");
            exit(0);
        }
        close(fd);

    }

    else
    {
        for(i = 0;i < 3;i++)
            wait(NULL);
        close(fd);
    }

    return 0;
}

//管道文件读端代码

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
    int fd = open("./myfifo",0666);

    char get[50];
    read(fd,get,50);
    printf("read:%s\n",get);
    return 0;
}

上述代码需要先运行写段代码再运行读端代码,因为写端代码才能穿创建管道文件,且假如有管道文件需要删除再原型代码。或者加入access()函数是否存在管道文件,不存在就创建管道文件。
注意点:
(1)管道文件不能使用函数lseek()定位
(2)最先写入管道的数据最先读取出来
(3)有名管道支持同时写入,具有写入原子性,linux的系统日志文件就是采用有名管道的写入原子性实现的,许多进程同时把运行状态消息写入管道,再从管道写到日志文件,这样子这些信息就不会因为同时写入而互相践踏
(4)关于open( )管道文件的阻塞问题:
在没有设置非阻塞的打开的情况下,不可以在只有写端或者读端的时候打开,会阻塞
在非阻塞模式可以先打开写端,写端会在read()阻塞,若先打开写端则会返回-1
(5)读写的阻塞和无名管道一样

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值