slb

Sleep on Low Battery
Log | Files | Refs | README | LICENSE

commit 159fd290d1bb6beb78bf775a4848122933713c95
parent d374e71cc2617393e7c01cc05bd15e8646df9347
Author: zerous Naveen Narayanan <zerous@nocebo.space>
Date:   Wed, 30 Oct 2019 20:41:36 +0100

Daemonize slb using daemoninit()

slb is intended to be used as a daemon and hence it doesn't need a
controlling terminal. This function is a template from Stevens APUE.

Diffstat:
Mslb.c | 53+++++++++++++++++++++++++++++++++++------------------
1 file changed, 35 insertions(+), 18 deletions(-)

diff --git a/slb.c b/slb.c @@ -10,6 +10,23 @@ #include "config.h" int +daemoninit(void) +{ + pid_t p; + + if ((p = fork()) == -1) + return -1; + else if (p != 0) + exit(0); + + setsid(); + chdir("/root"); + umask(0); + + return 0; +} + +int pwread(const char *bat) { char buf[4]; @@ -41,28 +58,28 @@ main(int argc, char **argv) int t; pid_t p; - - for (;;) { - tpow = 0; - - for (int i = 0; i < sizeof(bat)/sizeof(*bat); i++) { - tpow += pwread(bat[i]); - } + if (!daemoninit()) + for (;;) { + tpow = 0; - if (!pwread(ac) && (tpow < threshold)) { - if ((p = fork()) == -1) - err(1, "fork failed"); - else if (p > 0) { - wait(NULL); + for (int i = 0; i < sizeof(bat)/sizeof(*bat); i++) { + tpow += pwread(bat[i]); } - else if (p == 0) { - if ((t = execve(cmd,NULL,NULL)) == -1) - err(1, "execve failed"); + + if (!pwread(ac) && (tpow < threshold)) { + if ((p = fork()) == -1) + err(1, "fork failed"); + else if (p > 0) { + wait(NULL); + } + else if (p == 0) { + if ((t = execve(cmd,NULL,NULL)) == -1) + err(1, "execve failed"); + } } - } - sleep(delay); - } + sleep(delay); + } return 0; }