首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

向知名管道写入数据后,不能把数据读出来?

2013-01-01 
向有名管道写入数据后,不能把数据读出来???有名管道,是两个人一进程之间的相互通信,下面给管道写入数据,但

向有名管道写入数据后,不能把数据读出来???
有名管道,是两个人一进程之间的相互通信,下面给管道写入数据,但是并不能从管道中把数据读出来,还真的是让人纳闷啊:

(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");
        }
        /*′ò?a1üμà*/
        fd=open(FIFO_SERVER,O_WRONLY|O_NONBLOCK,0);

        if(argc==1)
        {
                printf("Please send something\n");
                exit(-1);
        }

        strcpy(w_buf,argv[1]);

        /* ?ò1üμàD′è?êy?Y */
        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         /* ′′?¨1üμà */
 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         /* ′ò?a1üμà */
 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(); /*?Yí££?μè′yD?o?*/
 44         unlink(FIFO); //é?3y???t
 45 }

这是为什么呢???还真的搞不懂,先去发个贴看看,看看是否有人能够帮忙!!!



[解决办法]
管道与权限也有关系的
我把 读端 fd=open(FIFO,O_RDWR,0);        改成可读可写,好像记得管道最好打开为 可读可写,不然会阻塞的

并且管道要同时存在  , 所以你先打开读端, 再写,可以读出来(两端同时存在,前提是打开管道可读可写)
[解决办法]
刚刚讲错了,可以只读,但是读端要先打开,正在读状态,前提是管道已经存在
[解决办法]
有名管道: 前提是两端同时在才可以通信,读端,写端,没有则阻塞
[解决办法]
非阻塞先打开读端, 再打开写端即可开始读写.

热点排行