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?
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.
那是原始过程中fork()的返回值...
pid_t child;
child = fork();
if (child == 0) {
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.