创建一个有名管道,解决无血缘关系的进程之间的通信;
创建管道的函数
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
首先创建一个有名管道myfifo 命令是: mkfifo myfifo
也可以直接使用上边的函数直接在代码中实现管道。
然后分别创建两个“.c”文件,fifo_w.c 和 fifo_r.c
fifo_w.c
#include <stdio.h>#include <stdlib.h>#include <unistd.h>
#include <sys/stat.h>#include <fcntl.h>#include <string.h>
void sys_err(char *str, int exitno)
{
perror(str);
exit(exitno);
}
int main(int argc, char *argv[])
{
int fd;
char buf[1024] = "hello xuxing\n";
if (argc < 2) {
printf("./a.out filename\n");
exit(1);
}
//fd = open(argv[1], O_RDONLY);
fd = open(argv[1], O_WRONLY);
if (fd < 0) {
sys_err("open", 1);
}
write(fd, buf, strlen(buf));
close(fd);
return 0;
}
fifo_r.c
#include <stdio.h>#include <stdlib.h>#include <unistd.h>
#include <sys/stat.h>#include <fcntl.h>#include <string.h>#include <sys/types.h>
void sys_err(char *str, int exitno)
{
perror(str);
exit(exitno);
}
int main(int argc, char *argv[])
{
int fd, len;
char buf[1024];
if (argc < 2) {
printf("./a.out filename\n");
exit(1);
}
fd = open(argv[1], O_RDONLY);
//fd = open(argv[1], O_WRONLY);
if (fd < 0) {
sys_err("open", 1);
}
len = read(fd, buf, sizeof(buf)); //读文件
write(STDOUT_FILENO, buf, len); //打印读取的内容
close(fd);
return 0;
}
运行结果:
创建的有名管道缓存的内容是不会存在磁盘中的。他只是在内核中的缓存中。