system()后获取子进程PID

发布于 2024-08-07 15:23:33 字数 310 浏览 2 评论 0原文

据我了解, system() 调用在内部使用 fork()exec() 但封装了它们以便于处理。

是否可以从使用 system() 调用创建的子进程中获取 PID?

目标:我希望能够在一定的超时后 SIGINT 任何子进程。我可以使用 fork()exec() 重建 system() 函数。但我所需要的只是孩子的PID,也许使用system()有捷径?

As far as I understand, the system() call uses internally fork() and exec() but encapsulates them for a easier handling.

Is it possible to get the PID from the child process created with the system() call?

Aim: I want to be able to SIGINT any child process after a certain timeout. I could rebuild the system() function by using fork() and exec(). But all I need is the child's PID and perhaps there is shortcut by using system()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

风追烟花雨 2024-08-14 15:23:33

通常,system() 是同步操作。这意味着在子进程退出之前它不会返回,即当 system() 返回时,子进程没有有效的 PID,因为子进程不再存在。

Typically, system() is a synchronous operation. This means it won't return until the child has exited, i.e. there is no valid PID for the child process when system() returns, since the child process no longer exists.

白日梦 2024-08-14 15:23:33

使用 system() 时没有办法(据我所知)。此外,使用 system() 还需要启动一个 shell 来执行您的命令,这使得这有点困难。您最好将其替换为 fork()exec()

There's no way (that I know of) when using system(). Besides, with system() there's the additional step of launching a shell which will execute your command, making this a tad more difficult. You're probably better off replacing it with fork() and exec().

何时共饮酒 2024-08-14 15:23:33

我遇到了这个问题。解决方法:

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

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

这可能并不总是有效,但大多数时候 system() 的 PID 是父进程的 pid +1(除非你有多个 fork)。

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).

淡笑忘祈一世凡恋 2024-08-14 15:23:33

但是,有一种方法可以通过 /proc 文件系统执行您想要的操作。您可以浏览进程目录(目录名称是 PID)并检查“状态”文件。其中每个都有一个 PPid 条目指定父 pid。

这样,如果您获得一个将进程的 PID 指定为 PPID 的“状态”文件,那么 /proc 文件系统中的文件夹名称就是您要查找的值。

However, there is a way of doing what you want via the /proc file system. You can go through process directories (directory names are PIDs) and check the "status" files. There's a PPid entry in each of them specifying the parent 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文