1 #define _POSIX_C_SOURCE 199309L
13 const int BUF_SIZE
= 1024;
15 const char PROMPT
[] = "\33[H" /* Move cursor 'home' */
16 "\33[J" /* Clear screen */
18 const char ACKNOWLEDGE
[] = "[OK]";
19 const char WAITING
[] = "[Waiting on lock...]\n";
20 const struct timespec ACKNOWLEDGE_DELAY
= {0, 300000000};
27 conf_t
parse_command_line(int argc
, char *argv
[]) {
32 for (int i
= 1; i
< argc
; i
++) {
33 if (strcmp(argv
[i
], "-i") == 0 && isatty(2))
35 if (strcmp(argv
[i
], "--no-fnctl-lock") == 0)
42 static void read_line(conf_t
*conf
, char *buf
) {
43 if (conf
->interactive
)
44 if (fputs(PROMPT
, stderr
) == EOF
)
45 die("I/O error writing prompt");
46 if (fgets(buf
, BUF_SIZE
, stdin
) == NULL
) {
48 die("I/O error reading line");
50 buf
[0] = '\0'; /* Unclear if fgets does this already */
53 die("Unexpected error reading line");
57 static void write_line(const char *now
, FILE *f
, const char *line
) {
59 die_err("Error opening output file");
60 if (fputs(now
, f
) == EOF
)
61 die("Error writing to output file");
62 if (fputc(' ', f
) == EOF
)
63 die("Error writing to output file");
64 if (fputs(line
, f
) == EOF
)
65 die("Error writing to output file");
68 static void take_lock(conf_t
*conf
, FILE *f
) {
69 if (!conf
->fcntl_lock
)
72 lock
.l_type
= F_WRLCK
;
73 lock
.l_whence
= SEEK_SET
;
78 die_err("Couldn't get file descriptor for locking");
79 if (fcntl(fd
, F_SETLK
, &lock
) == 0)
81 if (errno
!= EACCES
&& errno
!= EAGAIN
)
82 die_err("Couldn't take lock");
83 if (fputs(WAITING
, stderr
) == EOF
)
84 die("Error writing waiting message");
85 if (fcntl(fd
, F_SETLKW
, &lock
) == 0)
87 die_err("Couldn't take lock");
90 static void write_acknowledgment(conf_t
*conf
) {
91 if (conf
->interactive
) {
92 if (fputs(ACKNOWLEDGE
, stderr
) == EOF
)
93 die("Error writing acknowledgment");
94 if (nanosleep(&ACKNOWLEDGE_DELAY
, NULL
) == -1 && errno
!= EINTR
)
95 die_err("Error sleeping");
99 static void lock_and_write_line(conf_t
*conf
, const char *line
) {
100 const char *now
= encode_time(time(NULL
));
101 FILE *f
= fopen(FILENAME
, "a");
104 write_line(now
, f
, line
);
107 die_err("Error closing output file");
109 write_acknowledgment(conf
);
112 int main(int argc
, char *argv
[]) {
113 conf_t conf
= parse_command_line(argc
, argv
);
115 for (read_line(&conf
, buf
); buf
[0]; read_line(&conf
, buf
)) {
116 lock_and_write_line(&conf
, buf
);