Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / openmp / runtime / test / affinity / redetect.c
blobdba83b72cc42e50552071574a9744cafe3622d49
1 // RUN: %libomp-compile
2 // RUN: env KMP_AFFINITY=none %libomp-run
3 // REQUIRES: linux
5 // Check if forked child process resets affinity properly by restricting
6 // child's affinity to a subset of the parent and then checking it after
7 // a parallel region
9 #define _GNU_SOURCE
10 #include "libomp_test_affinity.h"
11 #include <omp.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <sys/wait.h>
15 #include <sys/types.h>
16 #include <unistd.h>
18 // Set the affinity mask of the calling thread to a proper subset of the
19 // original affinity mask, specifically, one processor less.
20 void set_subset_affinity(affinity_mask_t *mask) {
21 int cpu;
22 affinity_mask_t *original_mask = affinity_mask_alloc();
23 affinity_mask_copy(original_mask, mask);
24 // Find first processor to clear for subset mask
25 for (cpu = 0; cpu <= AFFINITY_MAX_CPUS; ++cpu) {
26 if (affinity_mask_isset(original_mask, cpu)) {
27 affinity_mask_clr(mask, cpu);
28 break;
31 affinity_mask_free(original_mask);
32 set_thread_affinity(mask);
35 int main(int argc, char **argv) {
36 char buf[1024] = {0};
37 char *other_buf;
38 size_t n;
39 int child_exit_status, exit_status;
40 affinity_mask_t *mask = affinity_mask_alloc();
41 get_thread_affinity(mask);
42 n = affinity_mask_snprintf(buf, sizeof(buf), mask);
43 printf("Orignal Mask: %s\n", buf);
45 if (affinity_mask_count(mask) == 1) {
46 printf("Only one processor in affinity mask, skipping test.\n");
47 exit(EXIT_SUCCESS);
50 #pragma omp parallel
52 #pragma omp single
53 printf("Hello! Thread %d executed single region in parent process\n",
54 omp_get_thread_num());
57 pid_t pid = fork();
58 if (pid < 0) {
59 perror("fork()");
60 exit(EXIT_FAILURE);
63 if (pid == 0) {
64 // Let child set a new initial mask
65 set_subset_affinity(mask);
66 #pragma omp parallel
68 #pragma omp single
69 printf("Hello! Thread %d executed single region in child process\n",
70 omp_get_thread_num());
72 affinity_mask_t *new_mask = affinity_mask_alloc();
73 get_thread_affinity(new_mask);
74 if (!affinity_mask_equal(mask, new_mask)) {
75 affinity_mask_snprintf(buf, sizeof(buf), mask);
76 fprintf(stderr, "Original Mask = %s\n", buf);
77 affinity_mask_snprintf(buf, sizeof(buf), new_mask);
78 fprintf(stderr, "New Mask = %s\n", buf);
79 affinity_mask_free(new_mask);
80 fprintf(stderr, "Child affinity mask did not reset properly\n");
81 exit(EXIT_FAILURE);
83 affinity_mask_free(new_mask);
84 exit_status = EXIT_SUCCESS;
85 } else {
86 pid_t child_pid = pid;
87 pid = wait(&child_exit_status);
88 if (pid == -1) {
89 perror("wait()");
90 exit(EXIT_FAILURE);
92 if (WIFEXITED(child_exit_status)) {
93 exit_status = WEXITSTATUS(child_exit_status);
94 } else {
95 exit_status = EXIT_FAILURE;
99 affinity_mask_free(mask);
100 return exit_status;