fork()
- int main(int argc, char* argv[])
- {
- fork();
- fork() && fork() || fork();
- fork();
- return 0;
- }
不算main这个进程自身,程序到底创建了19个进程。这里就需要注意&&和||运算符。A&&B,如果A=0,就没有必要继续执行&&B了;A非0,就需要继续执行&&B。A||B,如果A非0,就没有必要继续执行||B了,A=0,就需要继续执行||B。
子进程在创建时包括复制父进程缓冲队列的数据。
- int main() {
- pid_t fpid;//fpid表示fork函数返回的值
- //printf("fork!");
- printf("fork!/n");
- fpid = fork();
- if (fpid < 0)
- printf("error in fork!");
- else if (fpid == 0)
- printf("I am the child process, my process id is %d/n", getpid());
- else
- printf("I am the parent process, my process id is %d/n", getpid());
- return 0;
- }
执行结果如下:
fork!
I am the
parent process, my process id is 3361
I am the
child process, my process id is
3362
如果把语句printf("fork!/n");注释掉,执行printf("fork!");
则新的程序的执行结果是:
fork!I
am the parent process, my process id is 3298
fork!I am
the child process, my process id is
3299
程序的唯一的区别就在于一个/n回车符号,为什么结果会相差这么大呢?
这就跟printf的缓冲机制有关了,printf某些内容时,操作系统仅仅是把该内容放到了stdout的缓冲队列里了,并没有实际的写到屏幕上。但是,只要看到有/n
则会立即刷新stdout,因此就马上能够打印了。
运行了printf("fork!")后,“fork!”仅仅被放到了缓冲里,程序运行到fork时缓冲里面的“fork!”
被子进程复制过去了。因此在子进程度stdout缓冲里面就也有了fork!
。所以,你最终看到的会是fork! 被printf了2次!!!!
而运行printf("fork!
/n")后,“fork!”被立即打印到了屏幕上,之后fork到的子进程里的stdout缓冲里不会有fork!
内容。因此你看到的结果会是fork! 被printf了1次!!!!
浙公网安备 33010602011771号