【问题标题】:Getting pid before process execution on Linux在 Linux 上执行进程之前获取 pid
【发布时间】:2012-06-10 06:27:23
【问题描述】:

如何在进程实际执行之前打印进程 ID?有没有办法可以获取之前执行的进程 ID 并增加?

printf(<process id>);
execvp(process->args[0], process->args);

【问题讨论】:

  • 你为什么要这样做??
  • @obounaim 这实际上是您知道孩子的 PID 的方式,因此您知道如何处理他们 - fork() 返回由 exec 保留的孩子的 PID

标签: c linux process


【解决方案1】:

exec 系列系统调用会保留当前的 ​​PID,所以只需这样做:

if(fork() == 0) {
    printf("%d\n", getpid());
    execvp(process->args[0], process->args);
}

fork(2) 上分配新的 PID,这会将 0 返回给子进程,将子进程的 PID 返回给父进程。

【讨论】:

  • 所以我猜这可能不是 @Milk 所追求的(大概是分叉进程的 PID)——在你运行 fork 之前甚至内核都不知道。
【解决方案2】:

您需要 fork() 然后运行其中一个 exec() 函数。要从子进程获取数据,您需要在子进程和父进程之间进行某种形式的通信,因为 fork() 将创建父进程的单独副本。在本例中,我使用 pipe() 将数据从子进程发送到父进程。

int fd[2] = {0, 0};
char buf[256] = {0};
int childPid = -1;

if(pipe(fd) != 0){
   printf("pipe() error\n");
   return EXIT_FAILURE;
}

pid_t pid = fork();
if(pid == 0) {
   // child process
   close(fd[0]);
   write(fd[1], getpid(), sizeof(int));
   execvp(process->args[0], process->args);
   _exit(0)
} else if(pid > 0){
   // parent process
   close(fd[1]);
   read(fd[0], &childPid, sizeof(childPid));
} else {
   printf("fork() error\n");
   return EXIT_FAILURE;
}
printf("parent pid: %d, child pid: %d\n", getpid(), childPid);
return 0;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-11
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 2012-07-02
    • 2014-06-23
    相关资源
    最近更新 更多