簡體   English   中英

如何使用fork和execv獲取程序的pid

[英]How to get the pid of a program started with fork and 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?

它是由父級中的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。

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

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

嘿,我知道該代碼段。

我對上一個問題的回答是一個示例 ,說明如何將setrlimit()fork()exec()結合使用。 並不是要作為一個完整的示例,通常您會保存fork()的返回值以備后用(因為它是孩子的​​pid,這就是您想要的)。

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

您想要的是啟動此程序的進程的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值並根據自己是孩子還是父母來執行所需操作的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM