请教一下下面的代码
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(){
pid_t pid;
printf("fork()");
pid = fork();
if(pid < 0){
printf("error!");
exit(-1);
}else if(pid > 0){
printf("parent pid:%d\n", getpid());
}else if(pid == 0){
printf("child pid:%d\n", getpid());
}
printf("the last line, pid:%d\n", getpid());
}
输出是这样的:
snow@snow-desktop:~$ ./test
fork()parent pid:4408
the last line, pid:4408
fork()child pid:4409
the last line, pid:4409
我有几个疑问:
1.fork进程中的for语句与一般的语法不太一样?一般如果if后面的条件为true,则后面的else if不再做判断,而这里是会判断所有的条件?
2.执行fork后的语句(即sample code中的最后一行)是父进程和子进程都会执行的语句?
3.为什么sample code中的fork前的代码(即printf("fork()");)会执行两次?