1、使用文件进行进程间通信的理论依据是,fork之后,父子进程共享打开文件的文件描述符;也就是共享打开的文件。
2、父子进程通过文件进行进程间通信:
//父子进程共享打开的文件描述符,使用文件进行进程间通信
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/wait.h>
int main(void){
int fd1,fd2;
pid_t pid;
char buf[1024];
char *str="----test for shared fd in parent child process----\n";
pid=fork();
if(pid<0){
perror("fork error");
exit(1);
}
else if(pid==0){//son process
fd1=open("test.txt",O_RDWR|O_CREAT);
if(fd1<0){
perror("open1 error");
exit(1);
}
write(fd1,str,strlen(str));
printf("child write over!\n");
}
else{//parent process
fd2=open("test.txt",O_RDWR|O_CREAT);
if(fd2<0){
perror("open2 error");
exit(1);
}
sleep(1);//确保子进程先写入数据
printf("parent waitting for read...\n");
int len=read(fd2,buf,sizeof(buf));
write(STDOUT_FILENO,buf,len);
wait(NULL);
}
return 0;
}
运行结果: