【操作系统】Linux下进程间通信实现–匿名管道(PIPE),命名管道(FIFO)
程序源码:
file2fifo.c : (读取文件abc,写入命名管道)
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>
#include<fcntl.h>
int main(int argc,char *argv[]){
//创建命名管道
mkfifo("tp",0644);
//读端
int infd;
infd = open("abc",O_RDONLY);
if(-1 == infd){
perror("open");
exit(1);
}
//写端
int outfd;
outfd = open("tp",O_WRONLY);
if(-1 == outfd){
perror("open");
exit(1);
}
char buf[1024];
int n;
while((n = read(infd,buf,1024)) > 0){
//read尝试将文件描述符infd中的字节读取到缓冲区buf
//read返回成功读取到的字节数
write(outfd,buf,n);
// write返回:若成功则返回写入的字节数,若出错则返回-1
//write尝试将缓冲区buf中的字节写到文件描述符outfd中
}
//关闭读端写端
close(infd);
close(outfd);
return 0;
}
fifo2file.c : (读取管道,写入目标文件abc.bak)
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<errno.h>
#include<string.h>
#include<fcntl.h>
int main(int argc,char *argv[]){
//写端
int outfd;
outfd = open("abc.bak",O_WRONLY | O_CREAT | O_TRUNC,0644);
if(-1 == outfd){
perror("open");
exit(1);
}
//读端
int infd;
infd = open("tp",O_RDONLY);
if(-1 == infd){
perror("open");
exit(1);
}
char buf[1024];
int n;
//将从管道中读取到的数据写入文件abc.bak中
while((n = read(infd,buf,1024))>0){
write(outfd,buf,n);
}
close(infd);
close(outfd);
unlink("tp");
return 0;
}
makefile:
.PHONY:all
all:fifo2file file2fifo
fifo2file:fifo2file.c
gcc -o $@ $^
file2fifo:file2fifo.c
gcc -o $@ $^
.PHONY:clean
clean:
rm -f fifo2file file2fifo
程序运行结果:
首先运行file2fifo,将文件abc中的内容读取到管道中,然后进行进程等待:
然后运行fifo2file,将管道中的数据写入目标文件abc.bak中,从而实现文件的拷贝: