summaryrefslogtreecommitdiffstats
path: root/mdk-stage1/dietlibc/libpthread/pthread_atfork.c
blob: 70ca9f1621e01a8300a440eb873e0370f2744b17 (plain)
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
66
67
68
69
70
71
72
73
74
75
76
77
#include <unistd.h>
#include <errno.h>

#include <pthread.h>
#include "thread_internal.h"

#define PTHREAD_NUM_ATFORK 4

static struct _pthread_fastlock __atfork_struct_lock;
static struct {
  int used;
  void (*prepare)(void);
  void (*parent)(void);
  void (*child)(void);
} pthread_atfork_buf[PTHREAD_NUM_ATFORK];

int pthread_atfork(void (*prepare)(void),
		   void (*parent)(void),
		   void (*child)(void))
{
  int i,ret=-1;

  __NO_ASYNC_CANCEL_BEGIN;
  __pthread_lock(&__atfork_struct_lock);

  for (i=0;i<PTHREAD_NUM_ATFORK; ++i) {
    if (!(pthread_atfork_buf[i].used)) {
      pthread_atfork_buf[i].prepare=prepare;
      pthread_atfork_buf[i].parent=parent;
      pthread_atfork_buf[i].child=child;
      ret=0;
      break;
    }
  }

  __pthread_unlock(&__atfork_struct_lock);
  __NO_ASYNC_CANCEL_END;

  if (ret) ret=ENOMEM;
  return ret;
}

pid_t fork(void)
{
  pid_t pid;
  int i=PTHREAD_NUM_ATFORK;

  __NO_ASYNC_CANCEL_BEGIN;

  __TEST_CANCEL();
  __pthread_lock(&__atfork_struct_lock);

  while (i) {
    if (pthread_atfork_buf[--i].used)
      if (pthread_atfork_buf[i].prepare)
	pthread_atfork_buf[i].prepare();
  }

  pid=__libc_fork();

  if (pid>0) {		/* parent */
    for (i=0;i<PTHREAD_NUM_ATFORK;++i)
      if (pthread_atfork_buf[i].used)
	if (pthread_atfork_buf[i].parent)
	  pthread_atfork_buf[i].parent();
  } else if (pid==0) {	/* child */
    for (i=0;i<PTHREAD_NUM_ATFORK;++i)
      if (pthread_atfork_buf[i].used)
	if (pthread_atfork_buf[i].child)
	  pthread_atfork_buf[i].child();
  }

  __pthread_unlock(&__atfork_struct_lock);
  __NO_ASYNC_CANCEL_END;

  return pid;
}