2013-09-24 66 views
0

我必須執行命令並返回像cmd一樣的結果。如何獲得由popen創建的processID?

我剛剛發現了這個需求的唯一方法。我使用popen函數來執行命令並返回結果,然後使用pclose()函數關閉流和進程。

但是,如果命令永遠不會結束,例如「ping 8.8.8.8 -t」,我無法使用pclose()函數關閉進程。

如果我殺死由任務管理器由popen()創建的子進程,pclose函數工作正常。

如何獲得popen創建的processID殺死?

===================
人和:
如果我在Windows中使用_popen(),有什麼會我做的就是PID?

回答

0

popen()是使用execve()或其他一些exec函數編寫的。你要做的是(1)用... pipe()創建一對管道,它給你兩個文件描述符。一個是stdin,另一個是stdout。然後fork()並在子進程中執行execve()。在你調用fork()的時候,你得到了子進程。

popen()返回的文件是一個FILE *,爲了從pipe()中獲得該文件,你必須做一個fdopen()。不是太難。

這是相當多的工作,但如果你需要標識...

現在... MS-Windows下,這是一個有點不同,要使用CreatePipe()和CreateProcess的()或類似的功能。但結果是相似的。

0

使用

ps -o user,pid,ppid,command -ax | grep <process name> 

讓所有的子進程的信息。其實popen()做pipe()機制來執行命令。請參閱手冊頁popen()

在手冊頁,

 The environment of the executed command will be as if a 
child process were created within the popen() call using 
fork(2). If the application is standard-conforming (see 
standards(5)), the child is invoked with the call: 

execl("/usr/xpg4/bin/sh", "sh", "-c",command, (char *)0); 

otherwise, the child is invoked with the call: 

execl("/usr/bin/sh", "sh", "-c",command, (char *)0); 

The pclose() function closes a stream opened by popen() by 
closing the pipe. It waits for the associated process to 
terminate and returns the termination status of the process 
running the command language interpreter. This is the value 
returned by waitpid(3C). 

它清楚地統計是POPEN使用管道和叉子EXECL用於處理POPEN()函數。所以,你可以使用ps和aux來獲取所有的子進程信息。

+0

沒有人,它會如果我的項目有許多發生衝突具有相同名稱的子進程。 – quanrock

+0

從C/C++代碼執行命令,您必須使用fork()和exec() – Saravanan

1

wrapp一個popen函數的自己與 '管+叉+ DUP2 + EXEC('/斌/慶典 ' '-c',yourCommandHere)'

+0

嗨,如果我在Windows上使用_popen(),我該怎麼辦? – quanrock

相關問題