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 | |
David Sodman | bbcb052 | 2014-09-19 10:34:07 -0700 | [diff] [blame] | 7 | #include <stdio.h> |
| 8 | #include <stdlib.h> |
| 9 | #include <unistd.h> |
David Sodman | e46ea8a | 2015-03-13 15:47:12 -0700 | [diff] [blame^] | 10 | #include <string.h> |
David Sodman | bbcb052 | 2014-09-19 10:34:07 -0700 | [diff] [blame] | 11 | #include <fcntl.h> |
| 12 | |
David Sodman | e46ea8a | 2015-03-13 15:47:12 -0700 | [diff] [blame^] | 13 | #include "util.h" |
| 14 | |
| 15 | void sync_lock(bool acquire) |
| 16 | { |
| 17 | int lock; |
| 18 | int stat; |
| 19 | struct flock flock; |
| 20 | |
| 21 | lock = open("/run/frecon", O_CREAT, S_IRUSR | S_IWUSR | S_IROTH | S_IWOTH); |
| 22 | if (lock >= 0) { |
| 23 | memset(&flock, 0, sizeof(flock)); |
| 24 | flock.l_type = acquire ? F_WRLCK : F_UNLCK; |
| 25 | flock.l_whence = SEEK_SET; |
| 26 | flock.l_start = 0; |
| 27 | flock.l_len = 1; |
| 28 | stat = fcntl(lock, F_SETLK, &flock); |
| 29 | if (stat < 0) |
| 30 | LOG(ERROR, "Failed to operate on synch_lock(acquire = %d)", |
| 31 | acquire); |
| 32 | } |
| 33 | } |
| 34 | |
David Sodman | bbcb052 | 2014-09-19 10:34:07 -0700 | [diff] [blame] | 35 | |
| 36 | void daemonize() |
| 37 | { |
| 38 | pid_t pid; |
| 39 | int fd; |
| 40 | |
| 41 | pid = fork(); |
| 42 | if (pid == -1) |
| 43 | return; |
| 44 | else if (pid != 0) |
| 45 | exit(EXIT_SUCCESS); |
| 46 | |
| 47 | if (setsid() == -1) |
| 48 | return; |
| 49 | |
| 50 | // Re-direct stderr/stdout to the system message log |
| 51 | close(0); |
| 52 | close(1); |
| 53 | close(2); |
| 54 | |
| 55 | open("/dev/kmsg", O_RDWR); |
| 56 | |
| 57 | fd = dup(0); |
| 58 | if (fd != STDOUT_FILENO) { |
| 59 | close(fd); |
| 60 | return; |
| 61 | } |
| 62 | fd = dup(0); |
| 63 | if (fd != STDERR_FILENO) { |
| 64 | close(fd); |
| 65 | return; |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | #ifdef __clang__ |
| 70 | __attribute__((format (__printf__, 2, 0))) |
| 71 | #endif |
| 72 | void LOG(int severity, const char* fmt, ...) |
| 73 | { |
| 74 | va_list arg_list; |
| 75 | fprintf(stderr, "frecon: "); |
| 76 | va_start( arg_list, fmt); |
| 77 | vfprintf(stderr, fmt, arg_list); |
| 78 | va_end(arg_list); |
| 79 | fprintf(stderr, "\n"); |
| 80 | } |