简体   繁体   English

系统后获取子PID()

[英]Get the child PID after system()

As far as I understand, the system() call uses internally fork() and exec() but encapsulates them for a easier handling. 据我所知, system()调用使用内部fork()exec()但封装它们以便于处理。

Is it possible to get the PID from the child process created with the system() call? 是否可以从使用system()调用创建的子进程中获取PID?

Aim: I want to be able to SIGINT any child process after a certain timeout. 目标:我希望能够在一定的超时后SIGINT任何子进程。 I could rebuild the system() function by using fork() and exec() . 我可以使用fork()exec()重建system()函数。 But all I need is the child's PID and perhaps there is shortcut by using system() ? 但我需要的只是孩子的PID,也许有使用system()捷径?

Typically, system() is a synchronous operation. 通常, system()是同步操作。 This means it won't return until the child has exited, ie there is no valid PID for the child process when system() returns, since the child process no longer exists. 这意味着它不会在子项退出后返回,即system()返回时子进程没有有效的PID,因为子进程不再存在。

There's no way (that I know of) when using system() . 使用system()时没办法(我知道system() Besides, with system() there's the additional step of launching a shell which will execute your command, making this a tad more difficult. 此外,使用system()还有一个启动shell的附加步骤,它会执行你的命令,这使得这有点困难。 You're probably better off replacing it with fork() and exec() . 你最好用fork()exec()替换它。

I had this problem. 我有这个问题。 Solved it by: 解决了它:

int syspid,status;
pid_t ppid=getpid();
syspid=ppid+1

status=system(argv[1]); //here argv1 was another program;

This might not always work, but most of the time the system()'s PID is the parent's pid +1 (unless you have multiple forks). 这可能并不总是有效,但大多数情况下system()的PID是父pid +1(除非你有多个分叉)。

However, there is a way of doing what you want via the /proc file system. 但是,有一种方法可以通过/ proc文件系统执行您想要的操作。 You can go through process directories (directory names are PIDs) and check the "status" files. 您可以浏览进程目录(目录名称是PID)并检查“状态”文件。 There's a PPid entry in each of them specifying the parent pid. 每个都有一个PPid条目,指定父pid。

This way, if you get a "status" file which specifies the PID of your process as PPID, then its folder name in /proc file system is the value you are looking for. 这样,如果您获得一个“status”文件,该文件将进程的PID指定为PPID,那么/ proc文件系统中的文件夹名称就是您要查找的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM