我是bash的新人。我有这个小代码:
的 bash.sh
./mama
mama.cpp
#include <stdlib.h>
int main()
{
system("./shvili");
while(1){}
}
shvili.cpp
int main()
{
while(1){}
}
因为它显示mama
是shvili
进程的父级。我有这种情况,我不确切知道子进程的名称。所以我的问题是,如何从c ++中获取子进程的PID?(获得进程名称对我来说会更舒服。)
答案 0 :(得分:1)
一种至少通过bash检查的方法,如果情况如此,我不确切知道子进程的名称&#34;但是知道父进程的名称是唯一的,可以在bash
基于ps
,grep
,sed
使用(以删除较小pid的前导空格) ,tr
(将多个连续空间挤入一个)和cut
:
$> cat foo_bar.sh
#! /bin/bash
sleep 120
$> ./foo_bar.sh &
[1] 89239
$> ps -eo pid,ppid,args|grep -e " $(ps -eo pid,args| grep foo_bar.sh| grep -v grep| sed s/^\ //g |cut -f 1 -d ' ') "|grep -v foo_bar.sh| sed s/^\ //g | tr -s ' ' | cut -f 1,3 -d ' '
89241 sleep
因此,父进程的唯一名称用于确定父pid:
$> ps -eo pid,args| grep foo_bar.sh| grep -v grep| sed s/^\ //g |cut -f 1 -d ' '
89239
在子流程($(...)
)中进行评估,用于从另一个ps
调用中获取正确的行,以确定所寻找的子项和名称的pid(没有其他参数且没有事先知道孩子的名字。
注意 - 像bash一样,一些空格很重要 - 搜索模式末尾增加的空间:
... grep " $(ps -eo pid,args| grep foo_bar.sh| grep -v grep| cut -f 1 -d ' ') " ...
这有助于避免误报,例如当父pid为123时,没有填充空格,这将匹配包含这些数字的许多pid,如1234,12345,1123,......
更新(对评论作出反应):如果父进程为a_mama
(分支a_shvili
子进程)并且它是机器上唯一具有该名称的进程,那么以下应该有效:
$> p_proc="a_mama"
$> ps -eo pid,ppid,args|grep -e " $(ps -eo pid,args| grep ${p_proc}| grep -v grep| sed s/^\ //g | cut -f 1 -d ' ') "|grep -v ${p_proc}| sed s/^\ //g | tr -s ' ' | cut -f 1,3 -d ' '
12346 a_shvili
答案 1 :(得分:0)
您可以尝试使用pidof获取特定流程的pid。
实施例
char line[LEN];
FILE *cmd = popen("pidof...", "r");
fgets(line, LEN, cmd);
pid_t pid = strtoul(line, NULL, 10);
pclose(cmd);
答案 2 :(得分:0)
您知道子进程的名称是shvili
,如何启动它并且不知道它的名称。
如果您要了解孩子的PID
,请不要使用system
。 system
不是一个表现良好的程序,不要使用它。
而是使用fork
和exec
:
在父母那里:
#include <unistd.h>
int child_pid = fork();
if (child_pid == -1) {
//fork failed do something about it
} else if (child_pid == 0) {
//this runs for child
execl("shvili", NULL);
//if you get here then exec errored
} else {
//This runs for parent
//child_pid has child pid
//Add parent code hear.
wait(…);
}
说明: