簡體   English   中英

在Linux上執行流程之前獲取pid

[英]Getting pid before process execution on Linux

在實際執行流程之前,我將如何打印流程ID? 有沒有辦法可以獲得先前執行的進程ID並且只是遞增?

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

exec系列的系統調用保留當前的PID,所以只需:

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

fork(2)上分配新的PID,它返回0到子進程,子進程'PID到父進程。

你需要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;

暫無
暫無

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

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