2

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

IE

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

2 回答 2

8

系统调用的exec系列保留当前 PID,因此只需执行以下操作:

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

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

于 2012-06-10T06:29:40.987 回答
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;
于 2012-06-10T08:21:19.753 回答