有名管道
用于任意进程间的通信,涉及到特殊文件(p)
#include<sys/types.h>
#include<sys/stat.h>
int mkfifo(const char *pathname,mode_t mode);——创建有名管道
参数:
pathname:有名管道的名字(带路径)
mode:创建有名管道的权限
返回值:
成功返回0,失败返回-1,并返回错误码
注意:管道文件是由内核区域映射映射上来的,故其大小永远为0;
思路
首先通过mkfifo来创建管道文件并确定权限,通过文件IO的相关读写函数实现两个文件的读写操作。
相关代码
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
int main(int argc,char *argv[]){
if(argc!=2){
printf("User:%s<fifoname>\n",argv[0]);
exit(-1);
}
if(access(argv[1],F_OK)){ //通过access函数来判断是否存在了管道文件
if(mkfifo(argv[1],0666)){ // 创建管道文件
perror("mkfifo");
exit(-1);
}
}
int fd=open(argv[1],O_RDWR);
if(fd<0){
perror("open");
exit(-1);
}
char buf[40];
while(1){
bzero(buf,sizeof(buf));
scanf("%s",buf);
write(fd,buf,strlen(buf)); // 写入操作
}
return 0;
}
#include <stdio.h>
#include <stdlib.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("User:%s<fifoname>\n",argv[0]);
exit(-1);
}
if(access(argv[1],F_OK)){
if(mkfifo(argv[1],0666)){
perror("mkfifo");
exit(-1);
}
}
int fd=open(argv[1],O_RDWR);
if(fd<0){
perror("open");
exit(-1);
}
char buf[40];
while(1){
bzero(buf,sizeof(buf));
read(fd,buf,sizeof(buf)); // 读取操作,并打印
printf("%s\n",buf);
}
return 0;
}