如何获取由 popen 创建的进程 ID

How can I get the processID created by popen?

本文关键字:创建 popen 进程 ID 何获取 获取      更新时间:2023-10-16

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

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

但是如果命令永无止境,例如"ping 8.8.8.8 –t",我无法使用 pclose() 函数关闭进程。

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

如何获取由 popen 创建的进程 ID 来杀死?

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

自己用

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

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

你要做的是(1)用...pipe() 给你两个文件描述符。一个用于标准,另一个用于标准输出。然后你在子进程中 fork() 并执行 execve()。在你调用fork()的时候,你会得到子进程。

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

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

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

使用

   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 一起使用来获取所有子进程信息。