命令管道(FIFO)通信阻塞式实例

代码解析:

  1. 本题中使用mkfifo pipefile 在命令行状态下创建管道文件。
  2. 首先执行读文件程序,对第三方缓冲区内的内容进行读取操作。
  3. 对传入参数进行判断,是否含有管道文件的路径。如有函数继续运行,无则结束运行。
  4. 获取管道的路径信息,命令行输出管道信息,调用open打开FIFO文件(命名管道),停止执行,等待另一个open函数调用时唤醒。
  5. 执行写文件程序,正确获取到管道路径信息后,调用open打开FIFO文件,唤醒读文件程序继续执行,两个程序并行。读文件程序打印FIFO打开成功,写文件程序打印FIFO打开成功。
  6. 写程序进入睡眠,读程序运行至read时等待写程序调用write执行写操作向第三方缓存写数据,写程序沉睡结束调用write,写入信息成功,读程序获取到缓存中的数据,写程序打印写入成功并正常退出。读程序打印获取到的数据并正常退出。

 

#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<fcntl.h>
//写端
int main(int argc,char *argv[]){
    if (argc !=2){
        printf("not enough params,give pipefile name\n");
        exit(1);}
    char *pipefile;
    pipefile=argv[1];
    int fd;
    char *teststr="test strings!";
    printf("OPEN namedpipe--%s for write!\n",pipefile);
    fd=open(pipefile,O_WRONLY,0);//打开管道

    printf("OK!namedpipe--%s opened for write!\n",pipefile);
    //sleep(5);    
    write(fd,teststr,strlen(teststr));//写入信息
    printf("OK!namedpipe write successfully!\n");

    exit(0);
}

 

#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<fcntl.h>
//读端
int main(int argc,char *argv[]){
    if (argc !=2) {
        printf("not enough params,give    pipefile name\n");
       exit(1);}
    char *pipefile;
    pipefile=argv[1];
    char buf[100];
    int fd,i;
    printf("read open namedpipe!!\n");
    fd=open(pipefile,O_RDONLY,0);
    if (fd<0) {
        printf("no such namedpipe file !!\n");
        exit(-1); }
    printf("OK!namedpipe opened for read!\n");
    sleep(5);
    i=read(fd,buf,100);
    buf[i]=0;
    printf("OK!readed from namedpipe: %s!\n",buf);
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值