void cgi_run(const char* filename)
{
char buffer[1024] = { 0 };
int len;
int pfd[2];
int status;
pid_t pid;
/* create pipe */
if (pipe(pfd)<0)
return -1;
/* fork to execute external program or scripts */
pid = fork();
if (pid<0) {
return 0;
} else if (pid==0) { /* child process */
dup2(pfd[1], STDOUT_FILENO);
close(pfd[0]);
/* execute CGI */
execlp(filename, filename, NULL);
exit(0);
} else { /* parent process */
close(pfd[1]);
/* print output from CGI */
while((len=read(pfd[0], buffer, 1023))>0) {
buffer[len] = '\0';
printf("%s\n", buffer);
}
/* waiting for CGI */
waitpid((pid_t)pid, &status, 0);
}
}
使用 fork() 建立一个新的 Process,再去执行一支外部 CGI,而主程序会等待外部 CGI 的输出,再用 printf() 印出来 CGI 的输出内容。而比较令人骚不着头绪的部份,就是 pipe() 和 dup2() 的关系,使用 pipe() 可建立一组双向的管线,范例中是一组有两个整数值的数组 pfd,这是一条水管,从 pfd[0] 进入的东西会从 pfd[1] 出来,反之亦然,除此之外,它也是可以跨 Process,达成两个程序沟通的目的。除了建立 pipe,接着利用 dup2(),可以让管线去取代外部程序的标准输出(standard output),然后让主程序用管线接收。