栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

4、fork()复制进程

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

4、fork()复制进程

1、fork复制进程

进程:

2、父进程子进程
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 #include
  2 #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 #include
  2 #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 }

父进程子进程用的是同一块内存。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/333571.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号