c - 如何使用fork获取新创建的子进程的进程名称和进程id pid?

标签 c linux fork posix child-process

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

我想知道 child 活跃了多长时间以及何时终止。子进程的平均计时信息。

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?这是什么意思?

最佳答案

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

  • 您拥有子进程的 pid,因为它是由 fork 在父进程中返回的。 .

  • 您(可能)知道 child 的名字,因为在大多数情况下,您就是写 exec 的人。称呼。如果没有,用 child 的pid你可以 readlink /proc/<pid>/exe .

  • 如果您需要了解子进程运行时的统计信息,您可以调用 getrusage使用 RUSAGE_CHILDREN 选项。

  • 如果您只想要 child 完成后的统计数据,您可以使用 wait4 等待它

关于c - 如何使用fork获取新创建的子进程的进程名称和进程id pid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22908796/

相关文章:

c - 程序运行不正常 - C

linux - 如何在Linux中重命名列?

linux - bash 脚本 LAMP 创建 "yes"

c - 从C中的文本文件中提取和显示数据

C++ 捕获 fork 子 cout

c - C语言中的答案有歧义

c - 相关变量和操作的分组?

c - 为什么在此代码中字符串 a 附加到字符串 b

linux - 如何在 Linux 和 Unix 上等待 EPIPE?

c - 管道结构错误