代码:
int main(void)
{
printf("pid: %d\n", getpid());
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork Failed!");
exit(-1);
} else if (pid == 0) {
execv("sum", argv);
} else {
printf(" pid: %d\n", pid);
wait(NULL);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
pid: 280
pid: 281
Run Code Online (Sandbox Code Playgroud)
问题:
为什么两个pid不同.我认为它们应该是相同的,因为父节点是在else块中执行的,父节点是在fork之前执行的,所以它们应该是相同的,不是吗?
nos*_*nos 10
RETURN VALUE
On success, the PID of the child process is returned in the parent,
and 0 is returned in the child. On failure, -1 is returned in the parent,
no child process is created, and errno is set appropriately.
因此,在父进程中,fork()返回已创建的子进程的pid.