利用有名管道进行任意进程间通信

有名管道的特点

  1. 可用于任意进程之间通信。无名管道只能是父子进程或兄弟进程间通信。
  2. 打开管道时可以指定读写方式。无名管道只能是单工通信模式。
  3. 通过文件IO操作,内容放在内存中,当关闭读端和写端时,内容被释放。

示例要求


进程A:循环从键盘输入并写入有名管道myfifo,输入quit时退出。

进程B:循环统计进程A每次写入myfifo的字符串的长度


第一步:创建有名管道 (creat_fifo.c)

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<string.h>
#include<unistd.h>
int main(void)
{
   if(mkfifo("myfifo",0666)<0)/*创建管道文件,成功时返回0*/
   {                           /*权限 0666*/
   perror("mkfifo");           //有错误时返回
   exit(-1);
   }
   return 0;

}
~

第二步:向有名管道写入数据(write_fifo.c)

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<string.h>
#include<unistd.h>
#define N 32
int main()
{
        char buf[N];//定义一个数组
        int pfd;

        if((pfd = open("myfifo",O_WRONLY))<0)//open()打开管道文件,返回的是其文件描述符
        {                                     //以只写方式打开
          perror("open");
          exit(-1);

        }
        printf("myfifo is open\n");

        while(1)
        {
        fgets(buf,N,stdin);//从输入流stdin中读取32个字符到buf中
        if(strcmp(buf,"quit\n")==0)break; //若buf中字符为quit,则结束循环。不是则往下执行
        write(pfd,buf,N);//将buf中数据写入到管道中,写32位数据
        }
        close(pfd);//跳出循环时,关闭管道
        return 0;
}

第三步:读取有名管道中的数据( read_fifo.c)

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
#define N 32
int main(void)
{
    char buf[N];
    int pfd;
    if((pfd = open("myfifo",O_RDONLY))<0)//以只读方式打开管道文件,返回其文件描述符
 {
        perror("open"); //出错时返回
        exit(-1);

 }
        printf("myfifo is opem");//写入端退出时,read()返回0,则退出循环n
        while(read(pfd,buf,N)>0){//读管道数据
        printf("the length of string is %d\n",strlen(buf));
        }
        close(pfd);//结束时关闭管道
        return 0;
}

第四步:编译运行

/*分别进行编译*/
book@100ask:~/process$ gcc -o creat_fifo creat_fifo.c
book@100ask:~/process$ ./creat_fifo.c

book@100ask:~/process$ gcc -o write_fifo write_fifo.c
book@100ask:~/process$ ./write_fifo

book@100ask:~/process$ gcc -o read_fifo read_fifo.c
book@100ask:~/process$ ./read_fifo

结果

book@100ask:~/process$ ./write_fifo   //
myfifo is open     //提示管道已打开
welcome to china   //输入的字符串1
abc                //输入的字符串2
1234                //输入的字符串3
quit                //结束
book@100ask:~/process$
********************************
book@100ask:~/process$ ./read_fifo
the length of string is 17   //统计字符串1长度
the length of string is 4    //统计字符串2长度
the length of string is 5    //统计字符串3长度
book@100ask:~/process$

附加

利用 ll 命令,可以验证myfifo在磁盘中的大小为0,其是存放在内存中的。

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值