[英]How to get the pid of a program started with fork and execv
In this program, I start another process with 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(...);
}
How do I get the pid of the program that was started? 如何获取已启动程序的pid?
It's returned by the fork()
call in the parent, so you need to capture fork()
's return value in a variable. 它是由父级中的
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
}
In the child, the use of execv()
is irrelevant; 在孩子中,
execv()
的使用无关紧要; that doesn't change the pid. 不会改变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()
. 我对上一个问题的回答是一个示例 ,说明如何将
setrlimit()
与fork()
和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). 并不是要作为一个完整的示例,通常您会保存
fork()
的返回值以备后用(因为它是孩子的pid,这就是您想要的)。
Example code is not necessarily complete code. 示例代码不一定是完整的代码。
What you want is the pid
of the process that is starting this program. 您想要的是启动此程序的进程的
pid
。
The signature of fork
function is the following: fork
函数的签名如下:
#include <unistd.h>
pid_t fork(void);
and it returns: 它返回:
0
in the child 0
the pid of the child
in the parent the pid of the child
-1
if an error ocurred -1
如果发生错误 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
. 如果要获取创建的新进程(子进程)的
pid
,则必须检查返回的值是否大于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. 这可能会造成混淆,但事实是,执行
fork()
时,它将创建一个子进程,因此该程序分为两种。 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. 这就是为什么必须检查
pid
值并根据自己是孩子还是父母来执行所需操作的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.