Chinaunix首页 | 论坛 | 博客
  • 博客访问: 59461
  • 博文数量: 8
  • 博客积分: 189
  • 博客等级: 入伍新兵
  • 技术积分: 114
  • 用 户 组: 普通用户
  • 注册时间: 2012-04-15 15:23
文章分类

全部博文(8)

文章存档

2012年(8)

我的朋友

分类: 系统运维

2012-05-16 14:52:04

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之前就执行了。。。。
阅读(8406) | 评论(3) | 转发(1) |
给主人留下些什么吧!~~

星期五啦2012-05-17 21:03:53

恩,很不错,路过也表示顶。。

十七岁的回忆2012-05-16 21:01:26

呵呵,很详细啊~~博主可以多谢谢!拜读了!

夏冰软件2012-05-16 16:42:11

写的不错,支持一下