进程间通信之有名管道通信

命名管道(FIFO)

 

命名管道和基本的管道基本相同,但是也有一些显著的不同;

1)命名管道是在文件系统中,作为一个特殊的设备文件而存在的

2)不同祖先进程之间可以通过管道共享数据

3)当共享管道的进程执行完所有的I/O操作以后,命名管道将继续保存在文件系统中以便以后使用

4)管道只能由相关进程使用,他们共同的祖先进程创建了管道。但是,通过FIFO,不相关的进程也能交换数据

 

命名管道的创建:

    #include<sys/types.h>

    #include<sys/stat.h>

    int mkfifo(const char *pathname,mode_t mode);   filename为要创建的文件名;mode与文件的打开模式基本类似;

    返回:若成功则为0,若出错则返回-1

    一旦已经用mkfifo创建了一个FIFO,确实,一般的文件I/O函数(close,open,read,write,unlink等)都可用于FIFO;   

//pipe_read.c

 #include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <errno.h>

#include <fcntl.h>

#define FIFO "/tmp/myfifo"



int main(int argc,char *argv[])

{

    int fd;

    char buff[100];

    int n_read;

    if(mkfifo(FIFO,O_CREAT|O_EXCL)<0)

    {

        if(errno == EEXIST)

        {

            printf("cannot create fifo,have a fifo yet\n");

        }

    }

    printf("preparing for reading...\n");

    if((fd=open(FIFO,O_RDONLY,0766))<0)

    {

        printf("open fifo error!\n");

        exit(1);

    }

    while(1)

    {

        memset(buff,0,sizeof(buff));

        if((n_read=read(fd,buff,10))==-1)

        {

            if(errno == EAGAIN)

            {

                printf("no data yet\n");

            }

        }

        else

        {

             printf("read len = %d  str = %s from FIFO, len = %d\n", strlen(buff), buff, n_read);

        }

        sleep(1);

    }

    return 0;

}



//pipe_write.c

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <errno.h>

#include <fcntl.h>

#define FIFO "/tmp/myfifo"



int main(int argc,char *argv[])

{

    int fd;

    int n_write;

    char w_buff[100];

    if(argc==1)

    {

        printf("argc error\n");

        exit(1);

    }

    if((fd=open(FIFO,O_WRONLY,0766))<0)

    {

        if(errno == ENXIO)

        {

            printf("open error! no reading process\n");

        }

        printf("open error\n");

        exit(1);

        

    }

    strcpy(w_buff,argv[1]);

    while(1)

    {

        if((n_write=write(fd,w_buff,strlen(w_buff)))==-1)

        {

            if(errno == EAGAIN)

            {

                printf("The FIFO has not been read yet\n");

            }

            

        }

        else

        {

            printf("write str is %s to FIFO\n",w_buff);

        }

        sleep(1);

    }

    close(fd);

}

 

 

 

 

 


 

  

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值