把AUP上的FIFO小节又重温了一下,有几个问题需要注意:
1. open fifo时的顺序问题(只有当该FIFO为已写打开后,才可读)
2. open fifo时的EEXIST错误码处理(如果FIFO不存在我们才创建,否则直接打开用即可)
3.从FIFO中读数据的连续性(系统调用的原因(缓冲区))
写了个测试小程序:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#define FIFO1 "/tmp/fifo.1"
#define FIFO2 "/tmp/fifo.2"
void error_quit()
{
printf("exit...errno:%d,%s\n", errno, strerror(errno));
exit(-1);
}
int main(int argc, char **argv)
{
int rd = 0, wd = 0;
pid_t pid;
printf("Mkfifo for ipc....\n");
/* create two fifos */
if (-1 == mkfifo(FIFO1, 0666))
{
error_quit();
}
if (-1 == mkfifo(FIFO2, 0666))
{
unlink(FIFO1);
error_quit();
}
printf("FIFO create done!\n");
pid = fork();
if (pid < 0)/* fork error */
{
unlink(FIFO1);
unlink(FIFO2);
error_quit();
}
else if (pid == 0)
{
/* child */
int rd_child = 0, wd_child = 0;
rd_child= open(FIFO2, O_RDONLY);/* Read fifo 2 */
wd_child = open(FIFO1, O_WRONLY);/* Write fifo 1 */
if (rd_child < 0 || wd_child < 0)
{
/* open file error */
error_quit();
}
char msg[255] = "This is child write....\n";
size_t len_write = write(wd_child, msg, strlen(msg));
if (len_write <= 0)
{
printf("func:%s,line:%d,write fifo error!\n", __func__, __LINE__);
}
printf("Child write %d data to %s\n",len_write, FIFO1);
close(wd_child);
memset(msg, 0, sizeof(msg));
size_t len_rd = 0;
/*
while(len_rd < len_write)
{
size_t len_tmp = read(rd_child, msg+len_rd, len_write);
if (len_tmp <=0)
{
printf("read error\n");
}
len_rd += len_tmp;
}
printf("read msg from fifo2:%s\n", msg);
*/
if (read(rd_child, msg, sizeof(msg)) > 0)
{
printf("read msg from fifo2:%s\n", msg);
}
close(rd_child);
exit(0);
}
wd = open(FIFO2, O_WRONLY);
rd = open(FIFO1, O_RDONLY);
if (rd < 0 || wd < 0)
{
printf("read/write fd error...!\n");
error_quit();
}
char buf[255] = "This is parent write ...\n";
size_t len_write = write(wd, buf, strlen(buf));
if (len_write <= 0)
{
printf("func:%s,line:%d,write fifo error!\n", __func__, __LINE__);
}
printf("Parent write %d data to %s\n",len_write, FIFO2);
memset(buf, 0, sizeof(buf));
if (read(rd, buf, sizeof(buf)) > 0)
{
printf("read msg from fifo1:%s\n", buf);
}
close(rd);
close(wd);
waitpid(pid, NULL, 0);
unlink(FIFO1);
unlink(FIFO2);
return 0;
}