有名管道,是两个人一进程之间的相互通信,下面给管道写入数据,但是并不能从管道中把数据读出来,还真的是让人纳闷啊:
(1)向管道中写入数据:
#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"main(int argc,char** argv)
{
int fd;
char w_buf[100];
int nwrite;
if((mkfifo(FIFO_SERVER,O_CREAT|O_EXCL)<0)&&(errno!=EEXIST))
{
printf("peparing for reading bytes...\n");
}
/*´ò¿ª¹ÜµÀ*/
fd=open(FIFO_SERVER,O_WRONLY|O_NONBLOCK,0);if(argc==1)
{
printf("Please send something\n");
exit(-1);
}strcpy(w_buf,argv[1]);
/* Ïò¹ÜµÀдÈëÊý¾Ý */
if((nwrite=write(fd,w_buf,100))==-1)
{
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);
}(2)向管道中读出数据:
#include <sys/types.h>
2 #include <sys/stat.h>
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #define FIFO "/tmp/myfifo"
9
10 main(int argc,char** argv)
11 {
12 char buf_r[100];
13 int fd;
14 int nread;
15
16 /* ´´½¨¹ÜµÀ */
17 // if((mkfifo(FIFO,O_CREAT|O_EXCL)<0)&&(errno!=EEXIST))
18 // printf("cannot create fifoserver\n");
19
20 printf("Preparing for reading bytes...\n");
21
22 memset(buf_r,0,sizeof(buf_r));
23
24 /* ´ò¿ª¹ÜµÀ */
25 fd=open(FIFO,O_RDONLY|O_NONBLOCK,0);
26 if(fd==-1)
27 {
28 perror("open");
29 exit(1);30 }
31 // while(1)
32 // {
33 memset(buf_r,0,sizeof(buf_r));
34
35 if((nread=read(fd,buf_r,100))==-1)
36 {
37 if(errno==EAGAIN)
38 printf("no data yet\n");
39 }
40 printf("read %s from FIFO\n",buf_r);
41 sleep(1);
42 // }
43 pause(); /*ÔÝÍ££¬µÈ´ýÐźÅ*/
44 unlink(FIFO); //ɾ³ýÎļþ
45 }
这是为什么呢???还真的搞不懂,先去发个贴看看,看看是否有人能够帮忙!!!
http://bbs.csdn.net/topics/390227732(帖子地址)
最终版主答案是:非阻塞先打开读端, 再打开写端即可开始读写.
进程间通信,非阻塞和阻塞有什么区别呢?阻塞是不是“读端不用先打开,可以先写入,再读出数据呢??”