欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入
char buf_r[100];
int fd;
int nread;
if((mkfifo(FIFO,O_CREAT|O_EXCL)<0)&&(errno!=EEXIST)) //创建并执行
printf(”cannot create fifoserver\n”);
printf(”Preparing for reading bytes…\n”);
memset(buf_r,0,sizeof(buf_r));
fd=open(FIFO,O_RDONLY|O_NONBLOCK,0); //readonly 不阻塞
if(fd==-1)
{
perror(”open”);
exit(1);
}
while(1){
memset(buf_r,0,sizeof(buf_r));
if((nread=read(fd,buf_r,100))==-1){ //读取管道
if(errno==EAGAIN)
printf(”no data yet\n”);
}
printf(”read %s from FIFO\n”,buf_r);
sleep(1);
}
pause();
unlink(FIFO);
}
写管道:
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FIFO_SERVER “/tmp/myfifo”
int main(int argc,char** argv){
<span style=”white-space:pre”> </span>int fd;
<span style=”white-space:pre”> </span>char w_buf[100];
<span style=”white-space:pre”> </span>int nwrite;
<span style=”white-space:pre”> </span>
<span style=”white-space:pre”> </span>fd=open(FIFO_SERVER,O_WRONLY|O_NONBLOCK,0); //writeonly,管道已在read中创建,可以直接打开。
<span style=”white-space:pre”> </span>if(fd==-1)
<span style=”white-space:pre”> </span>if(errno==ENXIO)
<span style=”white-space:pre”> </span>printf(”open error; no reading process\n”);
<span style=”white-space:pre”> </span>if(argc==1)
<span style=”white-space:pre”> </span>printf(”Please send something\n”);
<span style=”white-space:pre”> </span>strcpy(w_buf,argv[1]);
<span style=”white-space:pre”> </span>if((nwrite=write(fd,w_buf,100))==-1){ //write
<span style=”white-space:pre”> </span>if(errno==EAGAIN)
<span style=”white-space:pre”> </span>printf(”The FIFO has not been read yet.Please try later\n”);
<span style=”white-space:pre”> </span>}
<span style=”white-space:pre”> </span>else
<span style=”white-space:pre”> </span>printf(”write %s to the FIFO\n”,w_buf);
}
[1][2]
醒来第一眼看见的是他,然后倒头继续睡。这就是我想要的幸福。