Nilorea Library
C utilities for networking, threading, graphics
Loading...
Searching...
No Matches
ex_signals.c
1
7#include <stdio.h>
8#include <stdlib.h>
9#include <stdbool.h>
10#include <stdint.h>
11#include <string.h>
12#include <stdbool.h>
13#include <errno.h>
14#include <signal.h>
15#include <assert.h>
16
17#include "nilorea/n_signals.h"
18#include "nilorea/n_log.h"
19
20#include <libgen.h>
21
22int divide_by_zero(void);
23void cause_segfault(void);
24int stack_overflow(void);
25void infinite_loop(void);
26void illegal_instruction(void);
27void cause_calamity(void);
28
29char* progname = NULL;
30
31int main(int argc, char* argv[]) {
32 (void)argc;
33 progname = argv[0];
34
35 // set_log_file( "ex_signals.log" );
38 // set_log_level( LOG_FILE );
39
40 n_log(LOG_DEBUG, "set_signal_handler");
41 set_signal_handler(basename(progname));
42
43 n_log(LOG_DEBUG, "cause_calamity");
44 cause_calamity();
45
46 return 0;
47}
48
49void cause_calamity(void) {
50 /* uncomment one of the following error conditions to cause a calamity of
51 your choosing! */
52 stack_overflow();
53 (void)divide_by_zero();
54 cause_segfault();
55 assert(false);
56 infinite_loop();
57 illegal_instruction();
58}
59
60int divide_by_zero(void) {
61 int a = 1;
62 int b = 0;
63 return a / b;
64}
65
66void cause_segfault(void) {
67 int* p = (int*)0x12345678;
68 *p = 0;
69}
70
71// that function was made to generate an error. Temporary disabling infinite recursion detection
72#pragma GCC diagnostic push
73#if defined(__GNUC__) && (__GNUC__ >= 12)
74#pragma GCC diagnostic ignored "-Winfinite-recursion"
75#endif
76int stack_overflow(void) {
77 int foo = 0;
78 (void)foo;
79 foo = stack_overflow();
80 return rand() % 1000;
81}
82#pragma GCC diagnostic pop
83
84/* break out with ctrl+c to test SIGINT handling */
85void infinite_loop(void) {
86 int a = 1;
87 int b = 1;
88 int c = 1;
89 while (a == 1) {
90 b = c;
91 c = a;
92 a = b;
93 }
94}
95
96void illegal_instruction(void) {
97 /* I couldn't find an easy way to cause this one, so I'm cheating */
98 raise(SIGILL);
99}
#define n_log(__LEVEL__,...)
Logging function wrapper to get line and func.
Definition n_log.h:69
#define LOG_DEBUG
debug-level messages
Definition n_log.h:64
#define LOG_STDERR
internal, default LOG_TYPE
Definition n_log.h:30
void set_log_level(const int log_level)
Set the global log level value ( static int LOG_LEVEL )
Definition n_log.c:91
void set_signal_handler(const char *progname)
Install a signal handler for progname.
Definition n_signals.c:367
Generic log system.
Signals general handling with stack printing, from https://gist.github.com/jvranish/4441299.