Statistics
| Branch: | Revision:

root / mainbox / util.c @ ea46eeca

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
  fgets(buf, BUF_SIZE, file);
32

    
33
  if (ferror(file)) {
34
    log_perror(filename);
35
    fclose(file);
36
    return NULL;
37
  }
38

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

    
43
  fclose(file);
44
  return strdup(buf);
45
}
46

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

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

    
73
  fprintf(file, "%d", getpid());
74

    
75
  fclose(file);
76
  return 0;
77
}
78

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

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

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

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

    
114
  fclose(file);
115
  return pid;
116
}