File: dlopen2.cpp

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 (99 lines) | stat: -rw-r--r-- 2,272 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/* To compile, use -DLIB3 to create libdlopen-lib3.so, -DLIB4 for
 * libdlopen-lib4.so, and define neither to create executable.
 * To run, do:  LD_LIBRARY_PATH=. ./dlopen2
 */

# include <dlfcn.h>
# include <unistd.h>
# include <stdio.h>
# include <stdio.h>
# include <stdlib.h>
# include <assert.h>

#if !defined(LIB3) && !defined(LIB4)
int (*fnc)(int result[2]);

int main(int argc, char* argv[])
{
  int lib = 1;
  void *handle = NULL;
  int result[2] = {0, 0};
  int i, answer;
  int cnt1 = 0, cnt2 = 0;

  printf("0: "); fflush(stdout);
  while (1) {
    if (handle != NULL)
      dlclose(handle);

    if (lib == 1) {
      handle = dlopen("libdlopen-lib3.so", RTLD_NOW);
      if (handle == NULL) {
        fprintf(stderr, "dlopen failed: %s\n", dlerror());
        exit(1);
      }
      /* See 'man dlopen' for example:  POSIX.1-2002 prefers this workaround */
      *(void **) (&fnc) = dlsym(handle, "fnc");
    }

    if (lib == 2) {
      handle = dlopen("libdlopen-lib4.so", RTLD_LAZY);
      if (handle == NULL) {
        fprintf(stderr, "dlopen failed: %s\n", dlerror());
        exit(1);
      }
      /* See 'man dlopen' for example:  POSIX.1-2002 prefers this workaround */
      *(void **) (&fnc) = dlsym(handle, "fnc");
    }

    assert(lib == 1 || lib == 2);
    for (i = 0; i < 5; i++) {
      answer = fnc(result);
      if (answer != result[lib - 1]) {
        fprintf(stderr, "lib %d returned wrong answer.\n", lib);
        exit(1);
      }
    }
    if (++cnt1 % 1000 == 0) {
      cnt2++;
      cnt1 = 0;
      printf("."); fflush(stdout);
      if (cnt2 % 50 == 0)
        printf("\n%d: ", cnt2 / 50);
      fflush(stdout);
    }
    lib = 3 - lib; /* switch libraries to load */

  }
  return 0;
}

#elif defined(LIB3)
extern "C" int fnc(int result[2]) {
    return ++(result[0]);
}

extern "C" int print_constructor() {
  int dummy = system("echo '    In LIB3::print_constructor'");
  if (dummy == -1) {
    perror("system failed.");
  }
  sleep(1);
  return 0;
}

#elif defined(LIB4)
extern "C" int fnc(int result[2]) {
    return ++(result[1]);
}

extern "C" int print_constructor() {
  int dummy = system("echo '    In LIB4::print_constructor'");
  if (dummy == -1) {
    perror("system failed.");
  }
  sleep(1);
  return 0;
}

#endif