File: pthread_atfork2.c

package info (click to toggle)
dmtcp 2.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,496 kB
  • sloc: cpp: 33,592; ansic: 28,099; sh: 6,735; makefile: 1,950; perl: 1,690; python: 1,241; asm: 138; java: 13
file content (71 lines) | stat: -rw-r--r-- 1,828 bytes parent folder | download
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
// This test is motivated by the usage in tclsh version 8.6
// It appears as if tclsh-8.6 creates a new thread within the child
//   routine registered by pthread_atfork().  However, some simple gdb tests
//   have not shown pthread_atfork() being used so far.  We should look
//   closely at the tclsh source code.

#define _POSIX_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pthread.h>

void *busy_loop(void *arg) {
  while (1) {
    sleep(5);
  }
}

#ifdef LIB
// Generates libpthread_atfork.so
void prepare(void) { printf("Before fork\n"); }
void parent(void) { printf("After fork in parent\n"); }
void child(void) {
  printf("After fork in child\n");
  pthread_t thread;
  pthread_create(&thread, NULL, busy_loop, NULL);
  // ENABLING THIS CODE CAUSES BUG IN dmtcp-2.4.2
  // Test if we reach here (new process), or if early thread creation hangs.
  // if (fork() == 0) { // if child
  //   busy_loop(NULL);
  // }
}

void myconstructor(void) __attribute__ ((constructor));
void myconstructor(void) {
    pthread_atfork(prepare, parent, child);
}

void foo(void) {}
#else
// Generates executable:  pthread_atfork
void foo(void);

int main ( int argc, char** argv )
{
  // Force linking of library compiled from this file with 'gcc -DLIB ...'
  foo();

  int childpid = fork();
  // ENABLING THIS CODE CAUSES BUG IN dmtcp-2.4.2
  // Test if we reach here (new process), or if early thread creation hangs.
  // if (fork() == 0) { // if child
  //   busy_loop(NULL);
  // }
  if ( childpid == 0 ) {  // if child
    int count = 0;
    while (1) {
      printf(" %2d ",count++);
      fflush(stdout);
      sleep(2);
    }
  }
  else {  // else parent
    waitpid(childpid, NULL, 0);
    printf("*** ERROR: child finished early.");
    return 1;
  }
  return 0;
}
#endif