blob: 34f93e00aa7a9c28d1f739b74bc875c0845fdc58 [file] [log] [blame]
David Sodmanbbcb0522014-09-19 10:34:07 -07001/*
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 Sodmanbbcb0522014-09-19 10:34:07 -07007#include <stdio.h>
8#include <stdlib.h>
9#include <unistd.h>
David Sodmane46ea8a2015-03-13 15:47:12 -070010#include <string.h>
David Sodmanbbcb0522014-09-19 10:34:07 -070011#include <fcntl.h>
12
David Sodmane46ea8a2015-03-13 15:47:12 -070013#include "util.h"
14
15void 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 Sodmanbbcb0522014-09-19 10:34:07 -070035
36void 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
72void 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}