pthread_atfork 2. Syntax 3. Param 4. Return Value 5. Remark 6. Example 7. Issue

Register fork handlers.

2. Syntax

1
2
3
int pthread_atfork(void (*prepare)(void),
void (*parent)(void),
void (*child)(void));

3. Param

prepare

The prepare fork handler.

parent

The parent fork handler.

child

The child fork handler.

4. Return Value

Upon successful, return zero; otherwise, an error number shall be returned to indicate the error.

5. Remark

  • The pthread_atfork() function shall declare fork handlers to be called before and after fork(), in the context of the thread that called fork(). The prepare fork handler shall be called before fork() processing commences. The parent fork handler shall be called after fork() processing completes in the parent process. The child fork handler shall be called after fork() processing completes in the child process. If no handling is desired at one or more of these three points, the corresponding fork handler address(es) may be set to NULL.

  • If a fork() call in a multi-threaded process leads to a child fork handler calling any function that is not async-signal-safe, the behavior is undefined.

  • The order of calls to pthread_atfork() is significant. The parent and child fork handlers shall be called in the order in which they were established by calls to pthread_atfork(). The prepare fork handlers shall be called in the opposite order.

6. Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <syscall.h>
#include <sys/types.h>
#include <sys/wait.h>


void PrepareWhenFork()
{
printf("%s %d n", __FUNCTION__, __LINE__);
}

void ParentWhenFork()
{
printf("%s %d n", __FUNCTION__, __LINE__);
}

void ChildWhenFork()
{
printf("%s %d n", __FUNCTION__, __LINE__);
}

void PrepareWhenFork1()
{
printf("%s %d n", __FUNCTION__, __LINE__);
}

void ParentWhenFork1()
{
printf("%s %d n", __FUNCTION__, __LINE__);
}

void ChildWhenFork1()
{
printf("%s %d n", __FUNCTION__, __LINE__);
}

int main(int argc, char *argv[])
{
if (pthread_atfork(PrepareWhenFork, ParentWhenFork, ChildWhenFork))
printf("%s %d n", __FUNCTION__, __LINE__);

if (pthread_atfork(PrepareWhenFork1, ParentWhenFork1, ChildWhenFork1))
printf("%s %d n", __FUNCTION__, __LINE__);

int i = fork();
if (i < 0)
{
printf("%s %d n", __FUNCTION__, __LINE__);
return -1;
}
else if (0 == i)
{
printf("%s %d n", __FUNCTION__, __LINE__);
return 0;
}
else
{
printf("%s %d n", __FUNCTION__, __LINE__);
wait(NULL);
}

return 0;
}
1
2
3
4
5
6
7
8
9
PrepareWhenFork1 26
PrepareWhenFork 11
ChildWhenFork 21
ChildWhenFork1 36
main 55
ParentWhenFork 16
ParentWhenFork1 31
main 60
Press <RETURN> to close this window...
1
The invocation of PrepareWhenFork() is early than ParentWhenFork() and ChildWhenFork(), the order of other is unknown.

7. Issue