今天看socket编程,遇到了fork函数,以前学过linux编程,对fork了解一点。可是都说它有两个返回值我就想不通了。
后来我又琢磨了会,查了查man手册,终于被我搞清楚了。fork既然是创建子进程的,那么说它返回两个值不如说是程序执行了两次:一次是父进程在执行,另一次是子进程在执行。
看看下面的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<span style="color: #339900;">#include <unistd.h> </span> <span style="color: #339900;">#include <stdio.h> </span> <span style="color: #0000ff;">int</span> main<span style="color: #008000;">(</span><span style="color: #008000;">)</span> <span style="color: #008000;">{</span> pid_t pid<span style="color: #008080;">;</span> <span style="color: #0000ff;">if</span><span style="color: #008000;">(</span><span style="color: #008000;">(</span>pid <span style="color: #000080;">=</span> fork<span style="color: #008000;">(</span><span style="color: #008000;">)</span><span style="color: #008000;">)</span> <span style="color: #000080;"><</span> <span style="color: #0000dd;">0</span><span style="color: #008000;">)</span> <span style="color: #008000;">{</span> <span style="color: #0000dd;">printf</span><span style="color: #008000;">(</span><span style="color: #ff0000;">"fork error<span style="color: #000099; font-weight: bold;">n</span>"</span><span style="color: #008000;">)</span><span style="color: #008080;">;</span> <span style="color: #0000ff;">return</span><span style="color: #008080;">;</span> <span style="color: #008000;">}</span> <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span> <span style="color: #008000;">(</span>pid <span style="color: #000080;">==</span> <span style="color: #0000dd;">0</span><span style="color: #008000;">)</span> <span style="color: #0000dd;">printf</span><span style="color: #008000;">(</span><span style="color: #ff0000;">"output from child:%d<span style="color: #000099; font-weight: bold;">n</span>"</span>,getpid<span style="color: #008000;">(</span><span style="color: #008000;">)</span><span style="color: #008000;">)</span><span style="color: #008080;">;</span> <span style="color: #0000ff;">else</span> <span style="color: #0000dd;">printf</span><span style="color: #008000;">(</span><span style="color: #ff0000;">"output from parent:%d<span style="color: #000099; font-weight: bold;">n</span>"</span>,getpid<span style="color: #008000;">(</span><span style="color: #008000;">)</span><span style="color: #008000;">)</span><span style="color: #008080;">;</span> <span style="color: #0000dd;">printf</span><span style="color: #008000;">(</span><span style="color: #ff0000;">"output %d<span style="color: #000099; font-weight: bold;">n</span>"</span>,pid<span style="color: #008000;">)</span><span style="color: #008080;">;</span> <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> <span style="color: #008000;">}</span> |
编译执行,结果如下:
output from child:4694
output 0
output from parent:4693
output 4694
可以很明显的看出,这个程序执行了两次,第一次fork返回了0,相当于是pid=4694的子进程在执行,第二次返回值为4694,也就是返回了子进程的pid,相当于是父进程在执行。
转载请注明:爱开源 » 你想的通吗–关于fork(2)函数