Linux中atfork的使用

来源:互联网 发布:鞋erp软件xyerp 编辑:程序博客网 时间:2024/05/24 04:19

#include <pthread.h>

int pthread_atfork(void (*prepare)(void), void (*parent)(void),
              void (*child)(void));

调用fork时,内部创建子进程前在父进程中会调用prepare,内部创建子进程成功后,父进程会调用parent,子进程会调用child。

看个例子

#include <stdio.h>#include <time.h>#include <pthread.h>#include <unistd.h>void prepare(void){printf("pid = %d prepare ...\n", static_cast<int>(getpid()));}void parent(void){printf("pid = %d parent ...\n", static_cast<int>(getpid()));}void child(void){printf("pid = %d child ...\n", static_cast<int>(getpid()));}int main(void){printf("pid = %d Entering main ...\n", static_cast<int>(getpid()));pthread_atfork(prepare, parent, child);fork();printf("pid = %d Exiting main ...\n",static_cast<int>(getpid()));return 0;}

运行结果
 pid = 24113 Entering main

 pid =24113 prepare...

 pid =24114 child...

 pid=24114 Exiting main....

 pid=24113 parent....

 pid=24113 Exiting main....

0 0