繁体   English   中英

如何使用fork和execv获取程序的pid

[英]How to get the pid of a program started with fork and execv

在此程序中,我使用execv启动了另一个进程。

if (fork() == 0) {
    struct rlimit limits;
    limits.rlim_cur = 10000000; // set data segment limit to 10MB
    limits.rlim_max = 10000000; // make sure the child can't increase it again
    setrlimit(RLIMIT_DATA, &limits);
    execv(...);
}

如何获取已启动程序的pid?

它是由父级中的fork()调用返回的,因此您需要在一个变量中捕获fork()的返回值。

pid_t child_pid = fork();
if (child_pid == -1) {
  // fork failed; check errno
}
else if (child_pid == 0) {  // in child
  // ...
  execv(...);
}
else {  // in parent
  // ...
  int child_status;
  waitpid(child_pid, &child_status, 0);  // or whatever
}

在孩子中, execv()的使用无关紧要; 不会改变pid。

那是原始过程中fork()的返回值...

pid_t child;
child = fork();
if (child == 0) {

嘿,我知道该代码段。

我对上一个问题的回答是一个示例 ,说明如何将setrlimit()fork()exec()结合使用。 并不是要作为一个完整的示例,通常您会保存fork()的返回值以备后用(因为它是孩子的​​pid,这就是您想要的)。

示例代码不一定是完整的代码。

您想要的是启动此程序的进程的pid

fork函数的签名如下:

#include <unistd.h>

pid_t fork(void);

它返回:

  • 孩子中的0
  • 父母the pid of the child
  • -1如果发生错误

如果要获取创建的新进程(子进程)的pid ,则必须检查返回的值是否大于0

在您的示例中:

pid_t pid = fork()

if (pid == 0) {
    struct rlimit limits;
    limits.rlim_cur = 10000000; // set data segment limit to 10MB
    limits.rlim_max = 10000000; // make sure the child can't increase it again
    setrlimit(RLIMIT_DATA, &limits);
    execv(...);
}
else if (pid > 0) {
    /* That's the value of the pid you are looking for */
}

这可能会造成混淆,但事实是,执行fork()时,它将创建一个子进程,因此该程序分为两种。 这就是为什么必须检查pid值并根据自己是孩子还是父母来执行所需操作的原因。

暂无
暂无

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

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