pthread_atfork(void (*prepare)(void),void (*parent)(void), void(*child)(void))
prepare在父进程fork创建子进程之前调用,这里可以获取父进程定义的所有锁;
void * thr_main(void * arg)
{
printf("parent process: new thread start \n");
pthread_mutex_lock(&lock);
printf("parent process: new thread get lock \n");
pid_t pid;
if((pid = fork()) < 0)
{
perror("fork");
pthread_exit(0);
}
else if(pid == 0) // child process
{
printf("child process: start\n");
printf("child process: unlock and get lock \n");
pthread_mutex_unlock(&lock);
pthread_mutex_lock(&lock);
printf("child process: exit\n");
}
else // parent process
{
sleep(10);
pthread_mutex_unlock(&lock);
printf("parent process: new thread unlock \n");
printf("parent process: new thread exit \n");
}
return ((void*)0);
}
int main(void)
{
printf("parent process: main thread start \n");
int err = 0;
pthread_t tid;
err = pthread_create(&tid, NULL, thr_main, NULL);
if(err != 0)
{
perror("pthread_create");
exit(1);
}
sleep(50);
printf("parent process: main thread exit \n");
return 0;
}
391



被折叠的 条评论
为什么被折叠?



