如何获取由 popen 创建的进程 ID
How can I get the processID created by popen?
我必须执行命令并返回像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 一起使用来获取所有子进程信息。
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 使用CMake创建QML插件
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- OpenCV EqualizeHist()从彩色图像创建黑白图像
- 试图在visual studio上用C++创建一个桌面应用程序
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 如何在C++20中创建模板别名的推导指南
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 链接到自行创建的dll失败
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++类内存结构中创建"spacer"?
- 终端不会为C++文件创建.exe文件吗
- 如何获取由 popen 创建的进程 ID