进程:
stu@stu-virtual-machine:~/Test/Forkex$ vi fork1.c stu@stu-virtual-machine:~/Test/Forkex$ gcc -o fork1 fork1.c stu@stu-virtual-machine:~/Test/Forkex$ ./fork1 s=parent,ppid=4067,pid=4390 s=child,ppid=4390,pid=4391 s=parent,ppid=4067,pid=4390 s=child,ppid=4390,pid=4391 s=child,ppid=4390,pid=4391 s=parent,ppid=4067,pid=4390 s=parent,ppid=4067,pid=4390 s=parent,ppid=4067,pid=4390 s=parent,ppid=4067,pid=4390 s=parent,ppid=4067,pid=4390
fork1.c
1 #include2 #include 3 #include 4 #include 5 int main() 6 { 7 int n=0; 8 char*s=NULL; 9 10 pid_t id=fork(); 11 assert(id!=-1);//断言复制进程成功了 12 13 if(id==0)//如果id=0代表的是子进程 14 { 15 s="child"; 16 n=3; 17 } 18 else 19 { 20 s="parent"; 21 n=7; 22 } 23 for(int i=0;i 父进程子进程交替输出,只有父进程结束之后子进程运行,在这里并发执行了。因为sleep了
stu@stu-virtual-machine:~/Test/Forkex$ ps -f UID PID PPID C STIME TTY TIME CMD stu 4067 4056 0 11:31 pts/0 00:00:00 bash stu 4422 4067 0 12:59 pts/0 00:00:01 ps -f父进程的父进程是bash
去掉sleep之后就会运行完父进程之后再运行子进程了。
stu@stu-virtual-machine:~/Test/Forkex$ gcc -o fork1 fork1.c stu@stu-virtual-machine:~/Test/Forkex$ ./fork1 s=parent,ppid=4067,pid=4436 s=parent,ppid=4067,pid=4436 s=parent,ppid=4067,pid=4436 s=parent,ppid=4067,pid=4436 s=parent,ppid=4067,pid=4436 s=parent,ppid=4067,pid=4436 s=parent,ppid=4067,pid=4436 s=child,ppid=2139,pid=4437 s=child,ppid=2139,pid=4437 s=child,ppid=2139,pid=4437源码:
1 #include2 #include 3 #include 4 #include 5 int main() 6 { 7 int n=0; 8 char*s=NULL; 9 10 pid_t id=fork(); 11 assert(id!=-1);//断言复制进程成功了 12 13 if(id==0)//如果id=0代表的是子进程 14 { 15 s="child"; 16 n=3; 17 } 18 else 19 { 20 s="parent"; 21 n=7; 22 } 23 for(int i=0;i 进程pid,获得pid 26 } 27 exit(0); 28 } 25 printf(“s=%s,ppid=%d,pid=%dn”,s,getppid(),getpid());//获得父> 进程pid,获得pid
26 }
27 exit(0);
28 }父进程子进程用的是同一块内存。



