Project

General

Profile

Statistics
| Branch: | Revision:

root / mainbox / util.c @ master

History | View | Annotate | Download (1.99 KB)

1
#include "util.h"
2
#include "log.h"
3
#include <stdlib.h>
4
#include <stdio.h>
5
#include <string.h>
6
#include <errno.h>
7
#include <unistd.h>
8
#include <sys/types.h>
9
#include <sys/stat.h>
10
#include <fcntl.h>
11

    
12
#define BUF_SIZE 1024
13

    
14
/*
15
 * read_file
16
 *
17
 * Reads the first line of a file. Returns NULL on error, or a pointer to a
18
 * malloc'd string which should later be freed.
19
 */
20
char *read_file(const char *filename) {
21
  char buf[BUF_SIZE];
22
  int len;
23
  FILE *file;
24

    
25
  file = fopen(filename, "r");
26
  if (file == NULL) {
27
    log_perror(filename);
28
    return NULL;
29
  }
30

    
31
  if (fgets(buf, BUF_SIZE, file) == NULL && ferror(file)) {
32
    log_perror(filename);
33
    fclose(file);
34
    return NULL;
35
  }
36

    
37
  len = strlen(buf);
38
  if (len > 0 && buf[len-1] == '\n')
39
    buf[len-1] = '\0';
40

    
41
  fclose(file);
42
  return strdup(buf);
43
}
44

    
45
/*
46
 * create_pid_file
47
 *
48
 * Creates PIDFILE containing the PID of the current process.  Returns 0 if
49
 * successful, or nonzero if there is an error or it already exists.
50
 */
51
int create_pid_file() {
52
  int fd;
53
  FILE *file;
54
  
55
  fd = open(PIDFILE, O_CREAT | O_EXCL | O_WRONLY, 0644);
56
  if (fd < 0) {
57
    if (errno == EEXIST)
58
      fprintf(stderr, "ERROR: tooltron is already running, or the pidfile "
59
          PIDFILE " is stale");
60
    else
61
      log_perror(PIDFILE);
62
    return 1;
63
  }
64

    
65
  file = fdopen(fd, "w");
66
  if (!file) {
67
    log_perror("fdopen");
68
    return 1;
69
  }
70

    
71
  fprintf(file, "%d", getpid());
72

    
73
  fclose(file);
74
  return 0;
75
}
76

    
77
/*
78
 * remove_pid_file
79
 *
80
 * Removes PIDFILE.
81
 */
82
void remove_pid_file() {
83
  if (unlink(PIDFILE))
84
    log_perror(PIDFILE);
85
}
86

    
87
/*
88
 * read_pid_file
89
 *
90
 * Returns the integer found in PIDFILE, or 0 if there was an
91
 * error.
92
 */
93
pid_t read_pid_file() {
94
  FILE *file;
95
  int pid;
96

    
97
  file = fopen(PIDFILE, "r");
98
  if (!file) {
99
    if (errno == ENOENT)
100
      fprintf(stderr, "ERROR: tooltron does not appear to be running\n");
101
    else
102
      perror(PIDFILE);
103
    return 0;
104
  }
105

    
106
  if (fscanf(file, "%d", &pid) != 1) {
107
    perror("fscanf");
108
    fclose(file);
109
    return 0;
110
  }
111

    
112
  fclose(file);
113
  return pid;
114
}