下面是设置nonblocking的示例,对于理解非常有用的
nonblocking_read.c
#include <unistd.h>
#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"
@H_502_24@int main(@H_502_24@int argc,@H_502_24@char *argv[]) {
@H_502_24@char buf_r[100];
@H_502_24@int fd;
@H_502_24@int nread;
@H_502_24@if ((mkfifo(FIFO_SERVER,O_CREAT | O_EXCL | O_RDWR) < 0) && (errno != EEXIST)) {
perror("can not creat fifo server");
exit(1);
}
@H_502_24@char cmd[100];
sprintf(cmd,"chmod 704 %s",FIFO_SERVER);
system(cmd);
printf("preparing for reading bytes .. \n");
memset(buf_r,0,@H_502_24@sizeof(buf_r));
fd = open(FIFO_SERVER,O_RDONLY | O_NONBLOCK,0);
@H_502_24@if (fd == -1) {
perror("open fail");
exit(1);
}
@H_502_24@while (1) {
memset(buf_r,@H_502_24@sizeof(buf_r));
@H_502_24@if ((nread = read(fd,buf_r,100)) == -1) {
@H_502_24@if (errno == EAGAIN) {
printf("no data yet\n");
}
}
printf("read %s from FIFO\n",buf_r);
sleep(1);
}
close(fd);
unlink(FIFO_SERVER);
}
nonblocking_write.c
#include <unistd.h>
#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"
@H_502_24@int main(@H_502_24@int argc,@H_502_24@char** argv)
{
@H_502_24@int fd;
@H_502_24@char w_buf[100];
@H_502_24@int nwrite;
fd = open(FIFO_SERVER,O_WRONLY | O_NONBLOCK,0);
@H_502_24@if (fd == -1)
{
perror("open error;no reading process");
exit(1);
}
@H_502_24@if (argc == 1)
{
printf("please send somenthing\n");
exit(1);
}
strcpy(w_buf,argv[1]);
@H_502_24@if ((nwrite = write(fd,w_buf,100)) == -1)
{
@H_502_24@if (errno == EAGAIN)
printf("the fifo has not been read yet.Please try later\n");
}
@H_502_24@else
printf("write %s to the fifo\n",w_buf);
close(fd);
@H_502_24@return 0;
}
测试结果