1

在这个程序中,我使用 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?

4

5 回答 5

3

它由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。

于 2011-04-27T04:07:13.557 回答
2

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

于 2011-04-27T04:05:47.693 回答
1
pid_t child;
child = fork();
if (child == 0) {
于 2011-04-27T04:07:45.040 回答
1

嘿,我认识那个代码片段。

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

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

于 2011-04-27T04:09:34.187 回答
1

你想要的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值并根据您是在孩子还是在父母中做您想做的事情。

于 2011-04-27T04:10:24.733 回答