命名管道非阻塞模式通信

命名管道非阻塞模式通信

分析:
在这里插入图片描述
代码:


//读端
#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>
#define FIFO "/root/myfifo"
void main(int argc,char** argv)
{   
	char buf_r[100];
    int  fd, nread;    
    int k = mkfifo(FIFO,O_CREAT|O_EXCL);			// 创建管道 
    if((k<0)&&(errno!=EEXIST))
        printf("cannot create fifoserver\n");   
    printf("Preparing for reading bytes...\n");    
    memset(buf_r,0,sizeof(buf_r));					//将buf_r用0填充
    /*
    void* memset(void *s, int c,size_t n);
    memset()会将参数s所指的内存区域前n个字节以参数c填入,然后返回指向s的指针。
    在编写程序时,若需要将某一数组做初始化,memset()会相当方便。
	*/   
	
    fd=open(FIFO,O_RDONLY|O_NONBLOCK,0);   			//打开命名管道FIFO
    if(fd==-1){
    	printf("open error!");
    }
    
    while(1) {
        memset(buf_r,0,sizeof(buf_r));        
        if((nread=read(fd,buf_r,100))==-1)  {		//read(fd,buf_r,100)  由已打开的文件fd读100个字节到buf_r中
            if(errno==EAGAIN)    printf("no data yet\n");
        }else
            printf("read %s from FIFO\n",buf_r);
        sleep(1);    
    }    

    pause(); 										//*暂停,等待信号*/
    unlink(FIFO); 									//删除文件
}


//写端
#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>
#define FIFO "/root/myfifo"
void main(int argc,char** argv)
{   
	int fd,j;				
    char w_buf[100];								//用于缓存参数传递的信息
    int nwrite;        								
    
    fd=open(FIFO,O_WRONLY|O_NONBLOCK,0);			//打开命名管道FIFO
    if(argc==1)
    {   
    	printf("Please send something\n");
    	exit(-1);        
    }
    strcpy(w_buf,argv[1]);	 	//将argv[1]字符串复制到w_buf 
    /*
    char *strcpy(char *dest, const char *src);
    将参数src字符串拷贝至参数dest所指的地址
    返回参数dest的字符串起始地址
    存在缓冲溢出的隐患,建议用strncpy()替换
	*/  
    //* 连续10次向管道写入数据 */
    for(j=0;j<10;j++){
    	/*
    	size_t strlen(const char *s);
    	返回字符串的长度,不包括结束字符"\0"
    	*/
        if((nwrite=write(fd,w_buf,strlen(w_buf)))==-1)
        //write(fd,w_buf,strlen(w_buf)	将w_buf所指内存写入strlen(w_buf)个字节到参数fd所指的文件
        {   if(errno==EAGAIN)
            	printf("The FIFO has not been read yet.Please try later\n");
        }else 
            printf("write %s to the FIFO\n",w_buf);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值