程序如下:void write_fifo(int argc, char *argv[]) { int fd; char w_buf[1024]; int nwrite;
if(fd==-1) if(errno==ENXIO) printf("open error; no reading process\n"); fd=open(FIFO_SERVER,O_WRONLY|O_NONBLOCK,0); if(argc==1) printf("Please send something\n"); strcpy(w_buf,argv[1]); if((nwrite=write(fd,w_buf,1024))==-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);
}
//--------------------------------------------------------------------------------------------------------- int readfifo() { 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");
执行读: read from FIFO read from FIFO read from FIFO read 212112121 from FIFO read from FIFO read from FIFO read from FIFO read from FIFO from FIFO read “ from FIFO read from FIFO read from FIFO read x‰ @ÎØðMÚ¢H+ÎØðM from FIFO read from FIFO no data yet read from FIFO
发布评论
评论(5)
回复 1# vdsvs
你存的是啥样的数据呢? 打印了不该打印的字符?
是不是不同步?我一个进程写,另外一个进程读。是不是呢? 需要吗??? 就是我写完后,另外一边能读出数据来,但随后就跟随几个乱码。需要考虑同步的问题?
程序如下:void write_fifo(int argc, char *argv[])
{
int fd;
char w_buf[1024];
int nwrite;
if(fd==-1)
if(errno==ENXIO)
printf("open error; no reading process\n");
fd=open(FIFO_SERVER,O_WRONLY|O_NONBLOCK,0);
if(argc==1)
printf("Please send something\n");
strcpy(w_buf,argv[1]);
if((nwrite=write(fd,w_buf,1024))==-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);
}
//---------------------------------------------------------------------------------------------------------
int readfifo()
{
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);
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);
memset(buf_r,0,sizeof(buf_r));
sleep(1);
}
pause();
unlink(FIFO);
}
这是典型的程序,需要考虑同步问题吗???
我操作过程如下:
我执行写:write 212112121 to fifo
执行读:
read from FIFO
read from FIFO
read from FIFO
read 212112121 from FIFO
read from FIFO
read from FIFO
read from FIFO
read from FIFO
from FIFO
read “ from FIFO
read from FIFO
read from FIFO
read x‰ @ÎØðMÚ¢H+ÎØðM from FIFO
read from FIFO
no data yet
read from FIFO
就是上面读到数据后紧跟着就是乱码,是那里问题呢???
两个进程读写这个管道应该不会有同步问题。
其实问题不大~~
在 strcpy(w_buf,argv[1]);前 加上一句话就应该没有问题了
memset(w_buf,'\0',sizeof(w_buf)); 原来谁知道w_buf 里面存的什么东西!