File: signal_send.cpp

package info (click to toggle)
llvm-toolchain-16 1%3A16.0.6-15~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,634,792 kB
  • sloc: cpp: 6,179,261; ansic: 1,216,205; asm: 741,319; python: 196,614; objc: 75,325; f90: 49,640; lisp: 32,396; pascal: 12,286; sh: 9,394; perl: 7,442; ml: 5,494; awk: 3,523; makefile: 2,723; javascript: 1,206; xml: 886; fortran: 581; cs: 573
file content (79 lines) | stat: -rw-r--r-- 1,833 bytes parent folder | download | duplicates (5)
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
// RUN: %clangxx -std=c++11 -O0 -g %s -o %t && %run %t 2>&1 | FileCheck %s

// sigandset is glibc specific.
// UNSUPPORTED: android, target={{.*(freebsd|netbsd).*}}

#include <assert.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>

sigset_t mkset(int n, ...) {
  sigset_t s;
  int res = 0;
  res |= sigemptyset(&s);
  va_list va;
  va_start(va, n);
  while (n--) {
    res |= sigaddset(&s, va_arg(va, int));
  }
  va_end(va);
  assert(!res);
  return s;
}

sigset_t sigset_or(sigset_t first, sigset_t second) {
  sigset_t out;
  int res = sigorset(&out, &first, &second);
  assert(!res);
  return out;
}

sigset_t sigset_and(sigset_t first, sigset_t second) {
  sigset_t out;
  int res = sigandset(&out, &first, &second);
  assert(!res);
  return out;
}

int fork_and_signal(sigset_t s) {
  if (pid_t pid = fork()) {
    kill(pid, SIGUSR1);
    kill(pid, SIGUSR2);
    int child_stat;
    wait(&child_stat);
    return !WIFEXITED(child_stat);
  } else {
    int sig;
    int res = sigwait(&s, &sig);
    assert(!res);
    fprintf(stderr, "died with sig %d\n", sig);
    _exit(0);
  }
}

void test_sigwait() {
  // test sigorset... s should now contain SIGUSR1 | SIGUSR2
  sigset_t s = sigset_or(mkset(1, SIGUSR1), mkset(1, SIGUSR2));
  sigprocmask(SIG_BLOCK, &s, 0);
  int res;
  res = fork_and_signal(s);
  fprintf(stderr, "fork_and_signal with SIGUSR1,2: %d\n", res);
  // CHECK: died with sig 10
  // CHECK: fork_and_signal with SIGUSR1,2: 0

  // test sigandset... s should only have SIGUSR2 now
  s = sigset_and(s, mkset(1, SIGUSR2));
  res = fork_and_signal(s);
  fprintf(stderr, "fork_and_signal with SIGUSR2: %d\n", res);
  // CHECK: died with sig 12
  // CHECK: fork_and_signal with SIGUSR2: 0
}

int main(void) {
  test_sigwait();
  return 0;
}