aboutsummaryrefslogtreecommitdiff
path: root/src/kill_everyone_and_reboot.cc
blob: 8b67f89d82132f9d13d082dd41adc334db7afa52 (plain)
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
/* vim: set sw=4 sts=4 et foldmethod=syntax : */

#include <sys/types.h>
#include <sys/mount.h>
#include <sys/reboot.h>
#include <unistd.h>
#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <stdbool.h>
#include <signal.h>

bool is_pid(const char * const c)
{
    for (const char * q = c ; *q ; ++q)
        if (*q < '0' || *q > '9')
            return false;

    return true;
}

void kill_everybody(const int sig)
{
    DIR * const dirh = opendir("/proc");
    if (! dirh)
    {
        perror("Couldn't opendir /proc");
        exit(EXIT_FAILURE);
    }

    fprintf(stderr, "Sending signal %d to: ", sig);
    const struct dirent * dp;
    while (((dp = readdir(dirh))))
    {
        if (! is_pid(dp->d_name))
            continue;

        const pid_t pid = atoi(dp->d_name);
        if (1 == pid || getpid() == pid)
            continue;

        fprintf(stderr, "%d ", pid);
        kill(pid, sig);
    }
    closedir(dirh);
    fprintf(stderr, "\n");
}

void remount_root_ro()
{
    fprintf(stderr, "Remounting / read-only");
    if (0 != mount("none", "/", "none", MS_RDONLY | MS_REMOUNT, ""))
    {
        perror("Couldn't remount / read-only");
        exit(EXIT_FAILURE);
    }
}

void sync_filesystems()
{
    fprintf(stderr, "Syncing filesystems");
    sync();
    sleep(1);
    sync();
}

void power_off()
{
    fprintf(stderr, "Rebooting");
    if (0 != reboot(RB_POWER_OFF))
    {
        perror("Couldn't call reboot syscall");
        exit(EXIT_FAILURE);
    }
}

int main(int, char *[])
{
    kill_everybody(SIGTERM);
    sleep(1);
    kill_everybody(SIGKILL);
    sleep(1);
    remount_root_ro();
    sync_filesystems();
    power_off();
    return EXIT_SUCCESS;
}