1 /* vi: set sw=4 ts=4: */
3 * circular buffer syslog implementation for busybox
5 * Copyright (C) 2000 by Gennady Feldman <gfeldman@gena01.com>
7 * Maintainer: Gennady Feldman <gfeldman@gena01.com> as of Mar 12, 2001
9 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
19 enum { KEY_ID = 0x414e4547 }; /* "GENA" */
21 static struct shbuf_ds {
22 int32_t size; // size of data written
23 int32_t head; // start of message list
24 int32_t tail; // end of message list
25 char data[1]; // data/messages
26 } *buf; // shared memory pointer
28 // Semaphore operation structures
29 static struct sembuf SMrup[1] = {{0, -1, IPC_NOWAIT | SEM_UNDO}}; // set SMrup
30 static struct sembuf SMrdn[2] = {{1, 0}, {0, +1, SEM_UNDO}}; // set SMrdn
33 static void error_exit(const char *str) ATTRIBUTE_NORETURN;
34 static void error_exit(const char *str)
36 //release all acquired resources
38 bb_perror_msg_and_die(str);
42 * sem_up - up()'s a semaphore.
44 static void sem_up(int semid)
46 if (semop(semid, SMrup, 1) == -1)
47 error_exit("semop[SMrup]");
50 static void interrupted(int sig ATTRIBUTE_UNUSED)
52 signal(SIGINT, SIG_IGN);
57 int logread_main(int argc, char **argv);
58 int logread_main(int argc, char **argv)
61 int log_semid; /* ipc semaphore id */
62 int log_shmid; /* ipc shared memory id */
63 smallint follow = getopt32(argc, argv, "f");
65 log_shmid = shmget(KEY_ID, 0, 0);
67 bb_perror_msg_and_die("can't find syslogd buffer");
69 // Attach shared memory to our char*
70 buf = shmat(log_shmid, NULL, SHM_RDONLY);
72 bb_perror_msg_and_die("can't access syslogd buffer");
74 log_semid = semget(KEY_ID, 0, 0);
76 error_exit("can't get access to semaphores for syslogd buffer");
78 // attempt to redefine ^C signal
79 signal(SIGINT, interrupted);
81 // Suppose atomic memory move
82 cur = follow ? buf->tail : buf->head;
85 #if ENABLE_FEATURE_LOGREAD_REDUCED_LOCKING
89 if (semop(log_semid, SMrdn, 2) == -1)
90 error_exit("semop[SMrdn]");
93 printf("head:%i cur:%d tail:%i size:%i\n",
94 buf->head, cur, buf->tail, buf->size);
96 if (buf->head == buf->tail || cur == buf->tail) {
100 sleep(1); /* TODO: replace me with a sleep_on */
103 puts("<empty syslog>");
107 #if ENABLE_FEATURE_LOGREAD_REDUCED_LOCKING
108 log_len = buf->tail - cur;
110 log_len += buf->size;
111 buf_data = xmalloc(log_len);
113 if (buf->tail >= cur)
117 memcpy(buf_data, buf->data + cur, j);
120 memcpy(buf_data + buf->size - cur, buf->data, buf->tail);
123 while (cur != buf->tail) {
124 fputs(buf->data + cur, stdout);
125 cur += strlen(buf->data + cur) + 1;
126 if (cur >= buf->size)
130 // release the lock on the log chain
133 #if ENABLE_FEATURE_LOGREAD_REDUCED_LOCKING
134 for (j = 0; j < log_len; j += strlen(buf_data+j) + 1) {
135 fputs(buf_data + j, stdout);
143 fflush_stdout_and_exit(EXIT_SUCCESS);