(5)FIFO的两种用途
[1] shell命令使用FIFO将数据从一条管道传送到另一条是,无需创建中间临时文件。
[2] 客户进程-服务端进程应用程序中,FIFO用作汇聚点,在客户进程和服务进程二者之间传递数据。
1.有一个服务器进程,它与很多客户进程有关。
2.每个客户进程都可将其请求写入到一个该服务器进程所创建的众所周知的FIFO中。
3.服务器进程从FIFO中读取多个客户进程所发送来的数据。
缺陷:服务器进程不能通过一个FIFO选择回答某个客户进程。
(6)注意
1. 通过FIFO可以多个客户进程向FIFO写,一个服务进程从FIFO中读出所有数据。
2. 不能服务器进程向FIFO写,多个客户端从FIFO中读取
通过测试,服务端进程向FIFO中写入数据时,多个以读方式打开FIFO的客户端进程中只有其中一个能够拿到数据,其他客户端拿不到数据。
(6)特性
1.FIFO内部维护有引用计数。
2.当最后一个引用FIFO的进程终止时,虽然FIFO的名字仍然保留在系统中,但是留在fifo中的数据已经被删除了。
通过FIFO可以多个客户进程向FIFO写,一个服务进程从FIFO中读出所有数据。
2. 不能服务器进程向FIFO写,多个客户端从FIFO中读取
通过测试,服务端进程向FIFO中写入数据时,多个以读方式打开FIFO的客户端进程中只有其中一个能够拿到数据,其他客户端拿不到数据。
// server.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>
#include <sys/wait.h>
#include <sys/acct.h>
#include <errno.h>
#include <sys/times.h>
#include <pthread.h>
#include <signal.h>
#define FIFOFILE_PATH "/workteam/zhouhouping/nfs/testCode/chapter15/FIFO/mfifo"
#define BUFSIZE 50
void delete_file(char *path)
{
char buf[100]={0};
sprintf(buf, "rm -rf %s", path);
system(buf);
}
int file_exists(const char *path)
{
return !access(path,F_OK);
}
int main()
{
int fd;
char buf[BUFSIZE+1]={0};
if (file_exists(FIFOFILE_PATH))
delete_file(FIFOFILE_PATH);
assert(0 == mkfifo(FIFOFILE_PATH, 0700)); // 0700:新建文件有可读可写可执行
assert(-1 != (fd = open(FIFOFILE_PATH, O_RDONLY))) ; // 阻塞, 直到有进程以写方式打开。
while (1)
{
memset(buf,0, BUFSIZE+1);
assert(-1 != read(fd, buf,BUFSIZE));
buf[BUFSIZE] = '\0';
printf("r: %s\n", buf);
}
return 0;
}
// client.c (运行多个客户端来表示多个客户端进程)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>
#include <sys/wait.h>
#include <sys/acct.h>
#include <errno.h>
#include <sys/times.h>
#include <pthread.h>
#include <signal.h>
#define FIFOFILE_PATH "/workteam/zhouhouping/nfs/testCode/chapter15/FIFO/mfifo"
#define BUFSIZE 50
void delete_file(char *path)
{
char buf[100]={0};
sprintf(buf, "rm -rf %s", path);
system(buf);
}
int file_exists(const char *path)
{
return !access(path,F_OK);
}
int main()
{
int fd;
char buf[BUFSIZE+1]={0};
assert(file_exists(FIFOFILE_PATH));
assert(-1 != (fd = open(FIFOFILE_PATH, O_WRONLY))) ; // 阻塞, 直到有进程以读方式打开。
while (1)
{
memset(buf,0, BUFSIZE+1);
scanf("%s", buf);
buf[BUFSIZE] = '\0';
assert(-1 != write(fd, buf,BUFSIZE));
}
return 0;
}