fork()、pipe()、dup2() 和 execlp() 的組合技法
對一般程式來說,管線(pipe)機制很少會用到,尤其對於在 Windows 底下的程式開發者來說,很可能前所未聞,而在 Unix-like 環境中常見的例子,就是往往在命令後面加上『|』,其意味使用『管子(pipe)』將內容導入另一個程式裡,如:『dmesg | grep ALSA』。在該例中,Shell 有趣的將 demsg 標準輸出(standard output)全數導入 grep 程式的標準輸入(standard input)中,再交由 grep 處理並找出存在 ALSA 字串的句子所在。   另一個情況,Web Server 在支援 CGI 時,也會使用到 pipe。這是最典型的例子,當 Web Server 欲執行一支外部 CGI Program 時,會利用 pipe 去模擬該 CGI 的標準輸入及輸出(Standard I/O)。以上說明當然只是大致上的做法,細節還需加上 fork() 和 dup2() 的配合,透過個範例可清楚瞭解這部份的實作。   這是一個簡單的範例:  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[...
