命名管道非阻塞模式通信
分析:
代码:
//读端
#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);
}
}