#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(void)
{
int fd;
int read_size;
char buf[20];
if((mkfifo("./myfifo", O_CREAT|O_EXCL) < 0) && (errno != EEXIST)) // !!
{
printf("fifo creat error\n");
exit(1);
}
printf("open and reading...\n");
if((fd = open("./myfifo", O_RDONLY|O_NONBLOCK,0)) < 0) //creat and open in O_NONBLOCK
{
printf("open fifo:%s\n", strerror(errno));
exit(1);
}
printf("opened, reading ..\n");
while(1)
{
memset(buf, 0, sizeof(buf)); // 数组要初始化
if((read_size = read(fd, buf, sizeof(buf))) < 0) //use right number of () 此处一定注意!容易出错!适当的加括号
{
printf("read error:%s\n", strerror(errno));
exit(1);
}
printf("read %s from fifo:%d\n", buf,read_size); // add '\n' in printf, or error
sleep(1); //sleep, execute slowly!
}
pause();
unlink("./myfifo");
}
|