popen函式的實現

2021-09-08 15:49:39 字數 1797 閱讀 7739

popen函式的實現包括一下幾步:

1、使用pipe()建立管道

2、使用fork()建立子程序

3、在子程序中呼叫exec族函式執行命令,通過管道將結果傳送至父程序

4、在主程序中等待子程序執行,子程序執行完成後將接收其結果,返回結果的檔案指標

類似與system(fork與exec函式的組合),popen在啟動另外乙個執行緒時,該執行緒有可能啟動失敗或者popen執行shell時失敗了,但這個時候popen本身不會報錯,直接就造成呼叫popen的父程序卡住了。可以通過驗證errno來避免。

下面是popen()在linux中的實現:/* 

*  popen.c     written by w. richard stevens */

#include    

#include    

#include    

#include    "ourhdr.h"

staticpid_t    *childpid = null;  

/* ptr to array allocated at run-time */

static

intmaxfd;  /* from our open_max(),  */

#define shell   "/bin/sh"

file*  

popen(const

char*cmdstring,const

char*type)  

if(childpid == null)   

if(pipe(pfd) < 0)  

return(null);   /* errno set by pipe() */

if( (pid = fork()) < 0)  

return(null);   /* errno set by fork() */

else

if(pid == 0)   

}else

}  /* close all descriptors in childpid */

for(i = 0; i < maxfd; i++)  

if(childpid[ i ] > 0)  

close(i);  

execl(shell, "sh"

, "-c"

, cmdstring, (char*) 0);  

_exit(127);  

}  /* parent */

if(*type == 'r'

)else

childpid[fileno(fp)] = pid; /* remember child pid for this fd */

return(fp);  

}int

pclose(file*fp)  

popen函式的實現

注 本文 本人有修改對 open max 的呼叫 popen函式的實現包括一下幾步 1 使用pipe 建立管道 2 使用fork 建立子程序 3 在子程序中呼叫exec族函式執行命令,通過管道將結果傳送至父程序 4 在主程序中等待子程序執行,子程序執行完成後將接收其結果,返回結果的檔案指標 類似與s...

自己實現popen函式

閒來無事,自己實現了popen函式mypopen,後來檢視了popen函式的原始碼發現自己實現的與其相差無幾,本函式與linux中的實現最大的不同是不需要用專門的pclose 函式來關閉檔案指標,用普通的fclose 即可,linux實現的 也會給出在下文,可以對比一下其中差異。主要通過pipe管道...

使用popen函式實現分頁顯示

include include include apue.h include include include include include include define pager int main int argc char argv if ferror fpin err sys fgets e...