有名管道的基本概念:
具体操作例程:
vi mkfifo.c 编辑下列代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
int ret;
int fd;
int nread;
char readbuff[50]={0};
ret = mkfifo("./myfifo",0755);
if(ret == -1)
{
printf("create mkfifo failed !\n");
return -1;
}
printf("create myfifo success !\n");
fd = open("./myfifo",O_RDONLY);
if(fd<0)
{
return -1;
}
printf("open file success !\n");
nread = read("fd,readbuff,50"); //readbuff用来存放读取到的从另一个进程的写进有名管道中的内容
printf("read %d byte from file,content:%s\n",nread,readbuff);
close(fd);
return 0;
}
ps:圈出来的就是生成的管道文件,两无亲缘关系的进程通过此文件进行读写通信,本文中的读进程就是上述的mkfifo.c
另一个进程write.c如下
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main()
{
int fd;
char *str="hello world";//将hello world写进通道里
fd = open("./myfifo",O_WRONLY);
if(fd<0)
{
return -1;
}
printf("open file success !\n");
write(fd,str,strlen(str));
close(fd);
return 0;
}
编译两个进程:
gcc mkfifo.c -o read
gcc write.c -o write
在终端中首先运行./read,再打开另一个终端运行./write 得到如下结果
结果表明:能在read进程中读取到write进程中的内容!
标签:int,亲缘,write,mkfifo,管道,有名,fd,myfifo,include From: https://blog.csdn.net/m0_57257049/article/details/140299900