2013-09-24 62 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

相关问题