命名管道
与匿名管道相比,命名管道使两个没有血缘关系的进程看到同一份临界资源。
管道创建:
可以用mkfifo
也可以用mknod
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char* filename, mode_t mode)
int mknod(const char* filename, mode_t mode | S_SIFIF0, (dev_t)0);
这两个函数都很会创建一个FIFO文件,这个文件见真实存在于系统文件中
,filename指定了该文件的名称,mode指定文件的读写权限。
管道文件创建好后,使两个进程实现通信,注意该通信是单向的。即一个读端一个写端。
测试代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#define PATH "/tmp/file.tmp"
#define SIZE 1024
int main(int argc, char const *argv[])
{
//创建一个命名管道文件,并设置权限对任何人可读可写可执行
int ret = mkfifo(PATH, 0666 | S_IFIFO);
if (-1 == ret){
perror("mkfifo");
return 1;
}
//打开该文件
int fd = open(PATH, O_WRONLY);
if (fd < 0){
perror("open");
return 2;
}
//buf是写入缓冲区
char buf[SIZE];
memset(buf, 0, sizeof(buf));
while (1){
scanf("%s",buf);
int ret = write(fd, buf, strlen(buf) + 1);
if (ret < 0){
perror("write");
return 3;
}
if (strncmp(buf, "quit", 4) == 0){
break;
}
}
close(fd);
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define SIZE 1024
#define PATH "/tmp/file.tmp"
int main(int argc, char const *argv[])
{
int fd = open(PATH, O_RDONLY);
if (fd < 0){
perror("open");
return fd;
}
//buf是读取数据的缓冲区
char buf[SIZE];
memset(buf, 0, sizeof(buf));
while (1){
int ret = read(fd, buf, sizeof(buf));
if (ret <= 0){
perror("read");
break;
}
printf("%s\n", buf);
if (strncmp(buf, "quit", 4) == 0){//???
break;
}
}
close(fd);
return 0;
}