有名管道
特点:
- 在磁盘上有这么一个文件, 当ls -l查看该文件时, 他的类型为p
- 是一个伪文件,占用磁盘大小永远为0.数据存储在内核里.有一个对应的缓冲区.
fifo文件可以用io函数进行操作
- open/close read/write 但不能用lseek
进程间通信:
- 两个不相干的进程可以通信
使用场景:
- 没有血缘关系的进程间通信
创建方式:
- 命令方式创建: mkfifo 管道名
- 函数方式创建: mkfifo函数
创建管道
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
int m = mkfifo(argv[1],0664);
if(m == -1) {
perror("mkfifo");
return -1;
}
return 0;
}
向管道写数据
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
int main(int argc, char *argv[]) {
char *msg = "this is a test!\n";
int fd =open(argv[1], O_WRONLY);
if(fd == -1) {
perror("open fifo faild");
return -1;
}
write(fd, msg, strlen(msg));
close(fd);
return 0;
}
向管道读取数据
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
int main(int argc, char *argv[]) {
char buf[128];
int fd =open(argv[1], O_RDONLY);
if(fd == -1) {
perror("open fifo faild");
return -1;
}
int r = read(fd, buf, 128);
write(1, buf, r);
close(fd);
return 0;
}