Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1879204
  • 博文数量: 1000
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 7921
  • 用 户 组: 普通用户
  • 注册时间: 2013-08-20 09:23
个人简介

storage R&D guy.

文章分类

全部博文(1000)

文章存档

2019年(5)

2017年(47)

2016年(38)

2015年(539)

2014年(193)

2013年(178)

分类: 系统运维

2016-07-29 17:03:26

1、我在程序调用这个函数:
int pthread_atfork(void (*prepare)(void),void (*parent)(void),void (*child)(void));
2、我再fork();//注意这里vfork()是不行的。
  这里就不介绍pthread_atfork里各个函数的用处。只谈谈顺序。我fork()之后,parent或child的运行顺序
我们不妨可以把它俩看着是在子进程或父进程中的一段程序。而且这段程序是最先运行的,不受sleep函数的
影响。
#include
#include
#include
#include
#include
#include
static  int i = 1;
void prepare(void)

     printf("prepare the i is %d\n",i);
 }
void parent(void)
{
   i++;
   printf("parent i is %d\n",i);
 
}
void child(void)
{
   i++;
   printf("child the i is %d\n",i);
}
int main()
{
   pid_t pid;
   printf("begin the i is %d\n",i);
 if(pthread_atfork(prepare, parent, child)!=0)
{
   printf("pthread_atfork error\n");
 }
 //sleep(2);
 if((pid=fork())<0)
 {
  perror("fork :");
 }
 else if(pid ==0)
 {  
  //sleep(1);
  printf("child\n");
 }
 else
 { 
  //sleep(1);
  printf("paraent\n");
  wait(pid);
  exit(0);
 }
}
./pthreadfork
begin the i is 1
prepare the i is 1
child the i is 2
child
parent i is 2
paraent
./pthreadfork
begin the i is 1
prepare the i is 1
parent i is 2
paraent
child the i is 2
child
这是没有用sleep是运行两次的结果。你可以在子进程或父进程中加sleep试试看。。但是你也决定不了是先调用parent还是调child,也就是说sleep只是在程序进入了子或父进程中之后,又让出运行权罢了。但是parent或child两个函数是在sleep之前就执行了。。。。
阅读(1072) | 评论(0) | 转发(0) |
0

上一篇:ms_protols

下一篇:smb.conf link

给主人留下些什么吧!~~