【问题标题】:How do get the process name & process id pid of newly created child process using fork?如何使用fork获取新创建的子进程的进程名称和进程id pid?
【发布时间】:2014-05-19 11:34:27
【问题描述】:

我正在使用 fork 创建子进程。现在我想知道使用putty的子进程的名称和进程id。我需要使用哪个命令来获取此信息。我正在尝试使用 ps 和 pstree。在创建新的子进程时如何给出子进程的名称?是否可以使用任何 linux/unix 命令获取此信息?

我想知道孩子活动的时间以及何时终止。子进程的平均时间信息。

root@mx6q:~# ps aux|grep "childprogram"
ps: invalid option -- 'a'
BusyBox v1.20.2 (2014-03-13 11:47:37 CET) multi-call binary.

Usage: ps

Show list of processes

        w       Wide output
        l       Long output
        T       Show threads

root@mx6q:~#



root@mx6q:~# ps | grep "childprogram"
 1407 root      1908 S    grep childprogram
root@mx6q:~# ps | grep "childprogram"
 1409 root      1908 S    grep childprogram
root@mx6q:~# ps | grep "childprogram"
 1411 root      1908 S    grep childprogram

家长:

root@mx6q:~# readlink /proc/670/exe
.asoundrc                   .gvfs/
.bashrc                     adit-30-09-2014.vnclicense
.gstreamer-0.10/            enable_usb_dr_host_mode.sh
root@mx6q:~# readlink /proc/670/exe

但我无法在 /proc/ 中找到子 pid?这是什么意思?

【问题讨论】:

  • 试试 ps aux|grep "childprogram"
  • root@mx6q:~# ps aux|grep "childprogram" ps: 无效选项 -- 'a' BusyBox v1.20.2 (2014-03-13 11:47:37 CET) 多路通话二进制。用法: ps 显示进程列表 w 宽输出 l 长输出 T 显示线程 root@mx6q:~#
  • @Mantosh 这是正确的方法还是我做错了什么......??
  • 我试过了:root@mx6q:~# ps | grep "childprogram" 1407 root 1908 S grep childprogram root@mx6q:~# ps | grep "childprogram" 1409 root 1908 S grep childprogram root@mx6q:~# ps | grep "childprogram" 1411 root 1908 S grep childprogram

标签: c linux fork posix child-process


【解决方案1】:

您将此标记为 C 并提到您是派生新进程的参与者,因此您可以在派生子进程的父进程中获得所有这些信息,但您需要更改代码以捕获它。

  • 您有孩子的 pid,因为它是由 fork 在父级中返回的。

  • 您(可能)拥有孩子的姓名,因为在大多数情况下,您是编写exec 电话的人。如果没有,您可以使用孩子的 pid readlink /proc/<pid>/exe

  • 如果您需要知道孩子在运行时的统计数据,您可以使用 RUSAGE_CHILDREN 选项调用 getrusage

  • 如果您只想要孩子完成后的统计数据,您可以通过wait4 等待它

【讨论】:

  • 我正在做所有这些练习,因为我总是从带有 ECHILD 错误号的 waitpid 获得 -1 返回值。有什么方法可以调试它失败的原因吗?我尝试了这两个: //pid_t returnValue = waitpid(Checksum_pid, &childStatus, 0); //pid_t returnValue = waitpid(Checksum_pid, &childStatus, WNOHANG);
  • 我使用了 readlink /proc/pid/exe 但我无法在列表中找到子 pid。这是什么意思。父 pid 可用吗?我在我的问题中更新了相同的内容。
  • 这些调用本身看起来还不错,这表明您在周围环境中的某个地方存在错误。您应该将代码缩减为所需的最少示例并提交另一个问题。这可能很简单,但仅凭此无法判断。
  • 您是否将 SIGCHLD 设置为 SIG_IGN?
  • 不,我该怎么做?我不知道。您能给我提供示例实现的参考吗?
【解决方案2】:

试试这个:

$ ps xf

并分析输出并使用 grep sed 和/或 awk 制作一些过滤器。

我对 BusyBox 不是很熟悉,因为我知道它是一个功能有限的小型发行版。

【讨论】:

  • -1。 BusyBox 不是“小型发行版”。它是一个实现许多标准 POSIX 工具的多调用库。
猜你喜欢
  • 2017-10-11
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
  • 2017-04-27
  • 2012-03-14
  • 2015-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多