chiark / gitweb /
941edc303dfe84046e0a8e085c6c24ba58cc2dad
[elogind.git] / src / sleep / sleep.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2012 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU Lesser General Public License as published by
10   the Free Software Foundation; either version 2.1 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   Lesser General Public License for more details.
17
18   You should have received a copy of the GNU Lesser General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <stdio.h>
23 #include <errno.h>
24 #include <string.h>
25
26 #include "log.h"
27 #include "util.h"
28
29 int main(int argc, char *argv[]) {
30         const char *verb;
31         char* arguments[4];
32         int r;
33         FILE *f;
34
35         log_set_target(LOG_TARGET_AUTO);
36         log_parse_environment();
37         log_open();
38
39         if (argc != 2) {
40                 log_error("Invalid number of arguments.");
41                 r = -EINVAL;
42                 goto finish;
43         }
44
45         if (streq(argv[1], "suspend"))
46                 verb = "mem";
47         else if (streq(argv[1], "hibernate"))
48                 verb = "disk";
49         else {
50                 log_error("Unknown action '%s'.", argv[1]);
51                 r = -EINVAL;
52                 goto finish;
53         }
54
55         f = fopen("/sys/power/state", "we");
56         if (!f) {
57                 log_error("Failed to open /sys/power/state: %m");
58                 r = -errno;
59                 goto finish;
60         }
61
62         arguments[0] = NULL;
63         arguments[1] = (char*) "pre";
64         arguments[2] = argv[1];
65         arguments[3] = NULL;
66         execute_directory(SYSTEMD_SLEEP_BINARY_PATH, NULL, arguments);
67
68         if (streq(argv[1], "suspend"))
69                 log_info("Suspending system...");
70         else
71                 log_info("Hibernating system...");
72
73         fputs(verb, f);
74         fputc('\n', f);
75         fflush(f);
76
77         r = ferror(f) ? -errno : 0;
78
79         if (streq(argv[1], "suspend"))
80                 log_info("System resumed.");
81         else
82                 log_info("System thawed.");
83
84         arguments[1] = (char*) "post";
85         execute_directory(SYSTEMD_SLEEP_BINARY_PATH, NULL, arguments);
86
87         fclose(f);
88
89 finish:
90
91         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
92
93 }