1

In this program, I start another process with 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(...);
}

How do I get the pid of the program that was started?

node ninja
  • 31,796
  • 59
  • 166
  • 254

5 Answers5

3

It's returned by the fork() call in the parent, so you need to capture fork()'s return value in a variable.

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
}

In the child, the use of execv() is irrelevant; that doesn't change the pid.

Wyzard
  • 33,849
  • 3
  • 67
  • 87
2

That's the return value from fork() in the original process...

Nicholas Riley
  • 43,532
  • 6
  • 101
  • 124
1
pid_t child;
child = fork();
if (child == 0) {
Dan D.
  • 73,243
  • 15
  • 104
  • 123
1

Hey, I recognise that code snippet.

My answer to your previous question was an example of how to use setrlimit() in combination with fork() and exec(). It wasn't intended as a complete example, and normally you would save the return value of fork() for later use (since it's the pid of the child, which is what you want here).

Example code is not necessarily complete code.

Community
  • 1
  • 1
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
1

What you want is the pid of the process that is starting this program.

The signature of fork function is the following:

#include <unistd.h>

pid_t fork(void);

and it returns:

  • 0 in the child
  • the pid of the child in the parent
  • -1 if an error ocurred

If you want to get the pid of the new process created (the child), you must check if the returned value is greather than 0.

In your example:

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 */
}

This can be confusing, but the thing is that when fork() is executed, it creates a child process, so the program kind of splits in two. That's why you must check for the pid value and do what you want depending of if you are in the child or in the parent.

Oscar Mederos
  • 29,016
  • 22
  • 84
  • 124