pipe是popen的底层函数
子进程调用 pipe3程序,传给pipe3 管道的文件描述符
pipe3对文件描述符进行读操作
实现不用进程之间的数据传输
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
int main(){
pid_t fork_result;
const char some_data[] = "123";
int file_pipes[2];
char buffer[BUFSIZ + 1];
int data_processed;
memset(buffer,'\0',sizeof(buffer));
if(pipe(file_pipes) == 0){
fork_result = fork();
//child thread
if(fork_result == 0){
sprintf(buffer,"%d",file_pipes[0]);
execl("pipe3","pipe3",buffer,(char *)0);
exit(0);
}else{
data_processed = write(file_pipes[1],some_data,strlen(some_data));
printf("%d - wrote %d bytes\n",getpid(),data_processed);
}
}
exit(0);
}
pipe3
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc,char *argv[]){
char buffer[BUFSIZ + 1];
int file_descriptor;
memset(buffer,'\0',sizeof(buffer));
sscanf(argv[1],"%d",&file_descriptor);
read(file_descriptor,buffer,BUFSIZ);
printf("get data:%s\n",buffer);
exit(0);
}