如何使用fork和execv启动程序的pid

时间:2011-04-27 04:04:45

标签: c++ process fork 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?

5 个答案:

答案 0 :(得分: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。

答案 1 :(得分:2)

这是原始进程中fork()的返回值...

答案 2 :(得分:1)

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

答案 3 :(得分:1)

嘿,我知道那段代码片段。

My answer to your previous question是关于如何将setrlimit()fork()exec()结合使用的示例。它不是一个完整的示例,通常你会保存fork()的返回值供以后使用(因为它是孩子的​​pid,这就是你想要的)

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

答案 4 :(得分: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值并根据你在孩子或父母身上做你想做的事情。