代码:
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);
}
}
输出:
pid: 280
pid: 281
问题:
为什么两个pid不同。我认为它们应该相同,因为父级是在 else
block 中执行的,而父级是在 fork 之前执行的,所以它们应该相同,不是吗?
最佳答案
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。
关于c - fork 和pid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6233707/