popen简版实现思路
popen()能像打开文件(file)一样打开进程(process),对进程进行类似于文件的读read()写write操作。
实现思路
- popen()打开指定的进程,返回类似于进程的描述符的文件指针,通过对文件指针的操作进而实现进程件的交互(读写)。
这里我们通过管道技术(单击查看)来实现popen()链接两个进程的功能。
使用fdopen()来将管道的两个端口(pipegate[0],pipegate[1])分别转换成文件指针,并把需要的端口返回给调用pipe()的进程。
具体来说,就是在进程中创建一个进程,在两个进程间创建一个管道,通过管道端口的文件指针来对管道进行读写,进而实现进程对进程的读写。
上代码:
(单看实现思路,不考虑错误处理)
#ifndef POPENX_H
#define POPENX_H
/*
author:wattercutter
purpose:make a popen
pro: popen.h(declear and define)
what's in program: return a file ptr(FILE*) of a process for read and write in process
*/
#include<stdio.h>
#include<unistd.h>
FILE* popenx(const char* command,const char* mode)
{
//pipegate for process
int songate;
int pargate;
//mode for pipegate
const int READ = 0;
const int WRIET = 1;
//judge the mode r/w
if(*mode == 'w'){
//if w then par-w,son-r
songate = READ;
pargate = WRITE;
}
else if(*mode == 'r'){
songate = WRITE;
pargate = READ;
}else return NULL;
//CREAT A PIPE
int pipegate[2];
pipe(pipegate);
//CREAT A PROCESS
int pid = fork();
//par code - include return
if(pid>0){
close(pipegate[songate]);//close no necessary gate
return fdopen(pipegate[pargate],mode);//return the file ptr(FILE*) of right gate
}
//son code - run the command exclp()
close(pipegate[pargate]);
dup2(pipegate[songate],songate);
close(pipegate[songate]);
//the first arg of execl needs total pathname,as execlp dose not need
execl("/bin/bash","sh","-c",command,NULL);
exit(1);
}
#ednif
这是我个人的代码和注释,如有兴趣了解更多,可以先看看前面的“管道技术”链接,然后找找“exec”系列调用的资料。
最后,推荐Bruce Molay的《Understanding of Unix/Linux Programming》这本书,非常友好。