xref: /llvm-project/compiler-rt/test/tsan/vfork.cpp (revision 1f4a0531b3fdb9b4747c155805393a91926fe058)
1 // RUN: %clangxx_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s
2 // UNSUPPORTED: ios
3 
4 #include <pthread.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <unistd.h>
8 #include <sys/types.h>
9 
10 int fds[2];
11 int X;
12 
Thread1(void * x)13 void *Thread1(void *x) {
14   X = 42;
15   write(fds[1], "a", 1);
16   return NULL;
17 }
18 
Thread2(void * x)19 void *Thread2(void *x) {
20   char buf;
21   while (read(fds[0], &buf, 1) != 1) {
22   }
23   X = 43;
24   return NULL;
25 }
26 
main()27 int main() {
28   pipe(fds);
29   int pid = vfork();
30   if (pid < 0) {
31     fprintf(stderr, "FAIL to vfork\n");
32     exit(1);
33   }
34   if (pid == 0) {  // child
35     // Closing of fds must not affect parent process.
36     // Strictly saying this is undefined behavior, because vfork child is not
37     // allowed to call any functions other than exec/exit. But this is what
38     // openjdk does.
39     close(fds[0]);
40     close(fds[1]);
41     _exit(0);
42   }
43   pthread_t t[2];
44   pthread_create(&t[0], NULL, Thread1, NULL);
45   pthread_create(&t[1], NULL, Thread2, NULL);
46   pthread_join(t[0], NULL);
47   pthread_join(t[1], NULL);
48   fprintf(stderr, "DONE\n");
49 }
50 
51 // CHECK-NOT: WARNING: ThreadSanitizer: data race
52 // CHECK-NOT: FAIL to vfork
53 // CHECK: DONE
54