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.
14 //#include <sys/types.h>
22 static const long KEY_ID = 0x414e4547; /* "GENA" */
24 static struct shbuf_ds {
25 int32_t size; // size of data written
26 int32_t head; // start of message list
27 int32_t tail; // end of message list
28 char data[1]; // data/messages
29 } *buf; // shared memory pointer
32 // Semaphore operation structures
33 static struct sembuf SMrup[1] = {{0, -1, IPC_NOWAIT | SEM_UNDO}}; // set SMrup
34 static struct sembuf SMrdn[2] = {{1, 0}, {0, +1, SEM_UNDO}}; // set SMrdn
36 static int log_shmid = -1; // ipc shared memory id
37 static int log_semid = -1; // ipc semaphore id
39 static void error_exit(const char *str) ATTRIBUTE_NORETURN;
40 static void error_exit(const char *str)
42 //release all acquired resources
45 bb_perror_msg_and_die(str);
49 * sem_up - up()'s a semaphore.
51 static void sem_up(int semid)
53 if (semop(semid, SMrup, 1) == -1)
54 error_exit("semop[SMrup]");
58 * sem_down - down()'s a semaphore
60 static void sem_down(int semid)
62 if (semop(semid, SMrdn, 2) == -1)
63 error_exit("semop[SMrdn]");
66 static void interrupted(int sig)
68 signal(SIGINT, SIG_IGN);
73 int logread_main(int argc, char **argv)
78 if (argc != 2 || argv[1][0]!='-' || argv[1][1]!='f' ) {
80 /* no options, no getopt */
85 log_shmid = shmget(KEY_ID, 0, 0);
87 error_exit("can't find circular buffer");
89 // Attach shared memory to our char*
90 buf = shmat(log_shmid, NULL, SHM_RDONLY);
92 error_exit("can't get access to syslogd buffer");
94 log_semid = semget(KEY_ID, 0, 0);
96 error_exit("can't get access to semaphores for syslogd buffer");
98 // attempt to redefine ^C signal
99 signal(SIGINT, interrupted);
101 // Suppose atomic memory move
102 cur = follow ? buf->tail : buf->head;
105 #ifdef CONFIG_FEATURE_LOGREAD_REDUCED_LOCKING
112 printf("head:%i cur:%d tail:%i size:%i\n", buf->head, cur, buf->tail, buf->size);
114 if (buf->head == buf->tail || cur == buf->tail) {
117 sleep(1); /* TODO: replace me with a sleep_on */
120 printf("<empty syslog>\n");
125 #ifdef CONFIG_FEATURE_LOGREAD_REDUCED_LOCKING
126 log_len = buf->tail - cur;
128 log_len += buf->size;
129 buf_data = xmalloc(log_len);
131 if (buf->tail >= cur) {
132 memcpy(buf_data, buf->data + cur, log_len);
134 memcpy(buf_data, buf->data + cur, buf->size - cur);
135 memcpy(buf_data + buf->size - cur, buf->data, buf->tail);
139 while (cur != buf->tail) {
140 fputs(buf->data + cur, stdout);
141 cur += strlen(buf->data + cur) + 1;
142 if (cur >= buf->size)
146 // release the lock on the log chain
149 #ifdef CONFIG_FEATURE_LOGREAD_REDUCED_LOCKING
150 for (j = 0; j < log_len; j += strlen(buf_data+j) + 1) {
151 fputs(buf_data + j, stdout);