Skip to content

Commit

Permalink
Add support for configurable redirect to /dev/null, issue #21
Browse files Browse the repository at this point in the history
Signed-off-by: Joachim Nilsson <[email protected]>
  • Loading branch information
troglobit committed Jan 15, 2018
1 parent f253900 commit 306bf0f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 15 deletions.
39 changes: 25 additions & 14 deletions src/service.c
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,18 @@ static int service_timeout_cancel(svc_t *svc)
return err;
}

static void redirect_null(void)
{
FILE *fp;

fp = fopen("/dev/null", "w");
if (fp) {
dup2(fileno(fp), STDOUT_FILENO);
dup2(fileno(fp), STDERR_FILENO);
fclose(fp);
}
}

static int is_norespawn(void)
{
return sig_stopped() ||
Expand Down Expand Up @@ -216,19 +228,24 @@ static int service_start(svc_t *svc)
if (svc->log.enabled) {
int fd;

if (svc->log.null) {
redirect_null();
goto logit_done;
}

/*
* Open PTY to connect to logger. A pty isn't buffered
* like a pipe, and it eats newlines so they aren't logged
*/
fd = posix_openpt(O_RDWR);
if (fd == -1) {
svc->log.enabled = 0;
goto logger_err;
goto logit_done;
}
if (grantpt(fd) == -1 || unlockpt(fd) == -1) {
close(fd);
svc->log.enabled = 0;
goto logger_err;
goto logit_done;
}

/* SIGCHLD is still blocked for grantpt() and fork() */
Expand Down Expand Up @@ -276,19 +293,11 @@ static int service_start(svc_t *svc)
}
}
#ifdef REDIRECT_OUTPUT
else {
FILE *fp;

fp = fopen("/dev/null", "w");
if (fp) {
dup2(fileno(fp), STDOUT_FILENO);
dup2(fileno(fp), STDERR_FILENO);
fclose(fp);
}
}
else
redirect_null();
#endif

logger_err:
logit_done:
sig_unblock();

if (svc->inetd.cmd)
Expand All @@ -307,7 +316,7 @@ static int service_start(svc_t *svc)
}
} else
#endif
if (svc->log.enabled)
if (svc->log.enabled && !svc->log.null)
waitpid(pid, NULL, 0);
exit(status);
} else if (log_is_debug()) {
Expand Down Expand Up @@ -519,6 +528,8 @@ static void parse_log(svc_t *svc, char *arg)
while (tok) {
if (!strcmp(tok, "log"))
svc->log.enabled = 1;
else if (!strcmp(tok, "null") || !strcmp(tok, "/dev/null"))
svc->log.null = 1;
else if (tok[0] == '/')
strlcpy(svc->log.file, tok, sizeof(svc->log.file));
else if (!strcmp(tok, "priority") || !strcmp(tok, "prio"))
Expand Down
3 changes: 2 additions & 1 deletion src/svc.h
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,8 @@ typedef struct svc {

/* Set for services we need to redirect stdout/stderr to syslog */
struct {
int enabled;
char enabled;
char null;
char file[64];
char prio[20];
char ident[20];
Expand Down

0 comments on commit 306bf0f

Please sign in to comment.