【发布时间】:2015-05-15 05:48:03
【问题描述】:
我决定学习 C,这是我使用的其中一本书中的 sn-p:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
pid_t result = fork();
if (result == -1){
fprintf(stderr, "Error\n");
return 1;
}
if (result == 0)
printf("I'm a child with PID = %d\n", getpid());
else
printf("I'm a parent with PID = %d\n", getpid());
return 0;
}
它的输出是:
I'm a parent with PID = 5228
I'm a child with PID = 5229
一切都清楚了,但result == 0 和result != 0 怎么可能同时出现?看起来这个变量存储了两个值,因为printf 指令被执行了两次。我知道,fork() 返回 0 和父母的 PID,但是 result 如何检查它是否在不同条件下返回 true?
【问题讨论】:
-
系统调用fork()用于创建进程。它不接受任何参数并返回一个进程 ID。
标签: c linux ipc multitasking