File: daemon.c

package info (click to toggle)
infnoise 0.3.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 27,304 kB
  • sloc: ansic: 2,177; sh: 251; python: 146; makefile: 65
file content (42 lines) | stat: -rw-r--r-- 945 bytes parent folder | download | duplicates (2)
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
// Functions used when running in the background

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>

#include "infnoise.h"

// Write PID in a file
static bool writePid(int32_t pid, char *fileName) {
    FILE *pidFile = fopen(fileName, "w");
    if(pidFile == NULL) {
        return false;
    }
    int ret = fprintf(pidFile, "%d\n", pid);
    fclose(pidFile);
    return (ret >= 0);
}

void startDaemon(struct opt_struct* opts) {
    if(!opts->daemon) {
        // No backgrounding, optionally write current PID
        if(opts->pidFileName != NULL) {
            writePid(getpid(), opts->pidFileName);
        }
        return;
    }
    int32_t pid = fork();
    if(pid < 0) {
        fputs("fork() failed\n", stderr);
        exit(1);
    }
    if(pid > 0) {
        // Parent
        exit(opts->pidFileName != NULL
             && !writePid(pid, opts->pidFileName));
    }
    // Child
}