keven@localhost systemCall]$ cat -n fork_example.c
1qI"Y$XuTw0 1 #include <stdio.h>
LUPA开源社区[
x0T'E[gBp,i 2 #include <unistd.h>
+dPpv;L9Ym+c0 3 #include <stdlib.h>
LUPA开源社区~}
x;e@ 4 #include <string.h>
LUPA开源社区Zq6N%zmU 5 #include <sys/types.h>
LUPA开源社区5u&G-i:N+F.@l'B0g'p 6 #include <sys/stat.h>
~^]!_8s~%~.xYQ0 7 #include <fcntl.h>
ya-[P%Y4rlYb8{0 8 #include <errno.h>
LUPA开源社区 n7n CU9s?-}1d[ 9 extern int errno;
LUPA开源社区(G2W8i;o6\2YJR~ 10
e!{%WdT4Q7s#Jl0 11 int main()
.ahQ R&J'zJ0 12 {
Xy;]EiYv!Z2[^M0 13 char buf[100];
LUPA开源社区/i~j:[7x:U 14 pid_t child_pid;
T!N}*F}5tp0 15 int fd;
LUPA开源社区3lm)\/P(TI,z 16 int status;
2x0j.e*H.c.Uf0 17
LUPA开源社区M8NpH;i:i;s 18 if((fd=open("temp",O_CREAT|O_TRUNC|O_RDWR,S_IRWXU))==-1)
? vo0X H9n3h0 19 {
LUPA开源社区1T?B(f
zj 20 printf("open error %d",errno);
LUPA开源社区N2qn|
dO I1d1@,\h 21 exit(1);
LUPA开源社区h;pmUMl 22 }
LUPA开源社区cf[b.cnz9w5|'f 23 strcpy(buf,"This is parent process write");
LUPA开源社区2dI%\1WJp$Fa 24 if((child_pid=fork())==0)
AB
[n6v2]6kk3z[?0 25 {
LUPA开源社区r6h1x]kT:^O 26 strcpy(buf,"This is child process write");
LUPA开源社区TT4L4Y3x2t] 27 printf("This is child process");
LUPA开源社区e Q6bt \#f\-|4{)u 28 printf("My PID(child) is %d\n",getpid());
LUPA开源社区\gg6@OW 29 printf("My parent PID is %d\n",getppid());
&FQ:{[)}7B0 30 write(fd,buf,strlen(buf));
LUPA开源社区 w)SG{7g0G Z Y7Q5p 31 close(fd);
LUPA开源社区:r6I,w;B+p7M&yu:c&Rm 32 exit(0);
V3v9t%Wx ] \-y7@8f0 33 }
CaV:Ho ~'B0 34 else
w(UR[-TcA G0 35 {
[*g)r~1Dn;M;m0 36 printf("This is parent process");
+\%sH"A%S+mi!a
O-i)~0 37 printf("My PID(parent) is :%d\n",getpid());
LUPA开源社区DE,h$CIVSO-u5_ 38 printf("My child PID is %d\n",child_pid);
LUPA开源社区'B6JH/iP{+^ 39 write(fd,buf,strlen(buf));
LUPA开源社区%q8o`7n3tg(E3~ 40 close(fd);
7]K R
Fr0 41 }
|8_ pa
B"dRo(^p0 42 wait(&status);
LUPA开源社区C'}0ojobK!O 43 return 0;
LUPA开源社区;y6O2nR\ 44 }
LUPA开源社区B j{#QW? em[keven@localhost systemCall]$ ./fork_example
LUPA开源社区FE%@%V
g0Cn;rBThis is child processMy PID(child) is 6207
*bB5|M]Z*m0My parent PID is 6206
K_,JA+M
M'u8x0This is parent processMy PID(parent) is :6206
Z-M]"x:MW+bp/?iyo0My child PID is 6207
LUPA开源社区_(BCn(v[keven@localhost systemCall]$