使用管道只能在相关的程序之间传递数据,即这些程序是由一个共同的祖先进程启动的。如何在不相关的进程之间交换数据呢?
可以用FIFO文件完成这项工作,它通常被称为命名管道(named pipe)。命名管道是一种特殊类型的文件,它在文件系统中以文件名的形式存在,但它的行为却和没有名字的管道类似。
可以在命名行上创建命名管道,也可以在程序中创建。命令行的命令是:
mkfifo filename
# include <sys/types.h>
# include <sys/stat.h>
int mkfifo(const char * pathname, mode_t mode)
pathname:FIFO文件名
mode:属性(见文件操作章节)
一旦创建了一个FIFO,就可用open打开它,一般的文件访问函数(close、read、write等)都可用于FIFO
/*****************************************************
Funcion List: fifo_read
*****************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#define FIFO_SERVER "/tmp/fifoserver"
int main()
{
int fd;
char r_buf[1000];
int r_num;
int ret;
memset(r_buf,0,sizeof(r_buf));
fd = open(FIFO_SERVER,O_RDONLY);
if (fd == -1)
{
perror("open fifo error!\n");
exit(-1);
}
while (1)
{
sleep(2);
memset(r_buf,0,sizeof(r_buf));
r_num = read(fd,r_buf,1000);
if (r_num == -1 && errno != EINTR)
{
perror("read error!\n");
exit(-1);
}
r_buf[r_num] = '\0';
printf("real read bytes :%d , is %s\n",r_num,r_buf);
}
unlink(FIFO_SERVER);
return 0;
}
/*****************************************************
Funcion List: fifo_write
*****************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#define FIFO_SERVER "/tmp/fifoserver"
int main()
{
int fd,ret;
char w_buf[1000];
int w_num;
memset(w_buf,0,sizeof(w_buf));
ret = mkfifo(FIFO_SERVER,O_CREAT|O_EXCL);
if(ret < 0 && errno != EEXIST)
{
perror("create fifo error !");
exit(-1);
}
fd = open(FIFO_SERVER,O_WRONLY);
if(fd == -1)
{
perror("open file error!\n");
exit(-1);
}
scanf("%s",w_buf);
w_num = write(fd,w_buf,strlen(w_buf));
if(w_num == -1 && errno != EINTR)
{
perror("write error !");
exit(-1);
}
else if(w_num > 0)
{
printf("real write num is %d\n",w_num);
}
return 0;
}