プロセスが実際に実行される前にプロセス ID を出力するにはどうすればよいですか? 以前に実行されたプロセス ID を取得してインクリメントする方法はありますか?
すなわち
printf(<process id>);
execvp(process->args[0], process->args);
syscall のexecファミリは現在の PID を保持するため、次のようにします。
if(fork() == 0) {
printf("%d\n", getpid());
execvp(process->args[0], process->args);
}
新しい PID はfork(2)に割り当てられ、子プロセスに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;