FIFO通信(first in first out)
FIFO 有名管道,实现无血缘关系进程通信。
- 创建一个管道的伪文件
- a.mkfifo testfifo 命令创建
- b.也可以使用函数int mkfifo(const char *pathname, mode_t mode);
- 内核会针对fifo文件开辟一个缓冲区,操作fifo文件,可以操作缓冲区,实现进程间通信–实际上就是文件读写
man 3 mkfifo
代码语言:javascript复制#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
注意事项:
FIFOs Opening the read or write end of a FIFO blocks until the other end is also opened (by another process or thread). See fifo(7) for further details.
打开fifo文件时候,read端会阻塞等待write端open,write端同理,也会阻塞等待另外一段打开。
代码示例: file_w.c 写端
代码语言:javascript复制#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, char *argv[]) {
if(argc != 2) {
printf("./a.out filename1n");
return -1;
}
printf("begin open wn");
int o_ret = open(argv[1], O_WRONLY);
printf("end open wn");
char buf[256];
int num = 0;
while (1) {
memset(buf, '#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, char *argv[]) {
if(argc != 2) {
printf("./a.out filename1n");
return -1;
}
printf("begin open wn");
int o_ret = open(argv[1], O_WRONLY);
printf("end open wn");
char buf[256];
int num = 0;
while (1) {
memset(buf, '