David Sodman | bbcb052 | 2014-09-19 10:34:07 -0700 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (c) 2014 The Chromium OS Authors. All rights reserved. |
| 3 | * Use of this source code is governed by a BSD-style license that can be |
| 4 | * found in the LICENSE file. |
| 5 | */ |
| 6 | |
| 7 | #include "util.h" |
| 8 | #include <stdio.h> |
| 9 | #include <stdlib.h> |
| 10 | #include <unistd.h> |
| 11 | #include <fcntl.h> |
| 12 | |
| 13 | |
| 14 | void daemonize() |
| 15 | { |
| 16 | pid_t pid; |
| 17 | int fd; |
| 18 | |
| 19 | pid = fork(); |
| 20 | if (pid == -1) |
| 21 | return; |
| 22 | else if (pid != 0) |
| 23 | exit(EXIT_SUCCESS); |
| 24 | |
| 25 | if (setsid() == -1) |
| 26 | return; |
| 27 | |
| 28 | // Re-direct stderr/stdout to the system message log |
| 29 | close(0); |
| 30 | close(1); |
| 31 | close(2); |
| 32 | |
| 33 | open("/dev/kmsg", O_RDWR); |
| 34 | |
| 35 | fd = dup(0); |
| 36 | if (fd != STDOUT_FILENO) { |
| 37 | close(fd); |
| 38 | return; |
| 39 | } |
| 40 | fd = dup(0); |
| 41 | if (fd != STDERR_FILENO) { |
| 42 | close(fd); |
| 43 | return; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | #ifdef __clang__ |
| 48 | __attribute__((format (__printf__, 2, 0))) |
| 49 | #endif |
| 50 | void LOG(int severity, const char* fmt, ...) |
| 51 | { |
| 52 | va_list arg_list; |
| 53 | fprintf(stderr, "frecon: "); |
| 54 | va_start( arg_list, fmt); |
| 55 | vfprintf(stderr, fmt, arg_list); |
| 56 | va_end(arg_list); |
| 57 | fprintf(stderr, "\n"); |
| 58 | } |