Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reopen STDIN and STDOUT as dev/null #28

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions ccan/daemonize/daemonize.c
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
* Environment. */
bool daemonize(void)
{
const char *dev_null = "/dev/null";
int fd;
pid_t pid;

/* Separate from our parent via fork, so init inherits us. */
Expand All @@ -25,11 +27,21 @@ bool daemonize(void)

/* Many routines write to stderr; that can cause chaos if used
* for something else, so set it here. */
if (open("/dev/null", O_WRONLY) != 0)
/* reopen STDIN */
if ((fd = open(dev_null, O_RDONLY)) == -1)
return false;
if (dup2(0, STDERR_FILENO) != STDERR_FILENO)
return false;
close(0);
if (dup2(fd, STDIN_FILENO) != STDIN_FILENO)
return false;
if (fd > STDERR_FILENO) close(fd);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be "if (fd == STDIN_FILENO)" right?

/* reopen STDOUT */
if ((fd = open(dev_null, O_WRONLY)) == -1)
return false;
if (dup2(fd, STDOUT_FILENO) != STDOUT_FILENO)
return false;
/* reopen STDERR */
if (dup2(fd, STDERR_FILENO) != STDERR_FILENO)
return false;
if (fd > STDERR_FILENO) close(fd);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And this should be !=, just for neatness...


/* Session leader so ^C doesn't whack us. */
setsid();
Expand Down
4 changes: 2 additions & 2 deletions ccan/daemonize/test/run.c
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ int main(int argc, char *argv[])
ok1(daemonized.ppid == 1);
#endif
ok1(daemonized.in_root_dir);
ok1(daemonized.read_from_stdin == EBADF);
ok1(daemonized.write_to_stdout == EBADF);
ok1(daemonized.read_from_stdin == 0);
ok1(daemonized.write_to_stdout == 0);
ok1(daemonized.write_to_stderr == 0);

return exit_status();
Expand Down