0

我必须执行命令并像 cmd 一样返回结果。

我刚刚找到了满足这个要求的唯一方法。我使用popen函数执行命令并返回结果,然后使用pclose()函数关闭流和进程。

但是如果命令永远不会结束,例如“ping 8.8.8.8 –t”,我无法使用 pclose() 函数关闭进程。

如果我通过任务管理器杀死由 popen() 创建的子进程,则 pclose 函数可以正常工作。

如何获取 popen 创建的 processID 来杀死?

==================
并且:
如果我在 Windows 中使用 _popen(),我需要做什么才能获得 PID?

4

3 回答 3

1

用 'pipe + fork + dup2 + exec('/bin/bash', '-c', yourCommandHere)' 自己包装一个 popen 函数

于 2013-09-24T06:09:42.550 回答
0

popen() 是使用 execve() 或其他一些 exec 函数编写的。

您要做的是(1)使用... pipe() 创建一对管道,它为您提供两个文件描述符。一个用于标准输入,另一个用于标准输出。然后你 fork() 并在子进程中执行 execve() 。在您调用 fork() 时,您将获得子进程。

popen() 返回的文件是一个 FILE*,要从 pipe() 获取它,你必须执行 fdopen()。不是太难。

这是相当多的工作,但如果你需要标识符......

现在...在 MS-Windows 下,这有点不同,您想使用 CreatePipe() 和 CreateProcess() 或类似的函数。但结果是相似的。

于 2013-09-24T05:18:53.007 回答
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 使用 pipe 和 fork 和 execl 来处理 popen() 函数。因此,您可以使用 ps 和 aux 来获取所有子进程信息。

于 2013-09-24T05:59:46.103 回答