Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linux : close or redirect standard output to /dev/null after detaching from terminal

We have a linux code that does detaching from terminal based on implementation found on http://www.itp.uzh.ch/~dpotter/howto/daemonize.

Here a code snippet from it :

....
freopen( "/dev/null", "r", stdin);
freopen( "/dev/null", "w", stdout);
freopen( "/dev/null", "w", stderr);

kill( parent, SIGUSR1 );
}

Instead of redirecting to /dev/null I can just close standard file descriptors in the following way and achieve the same result:

close(STDIN_FILENO);     
close(STDOUT_FILENO); 
close(STDERR_FILENO);

For now, I'm a bit stuck with what approach to use : redirect or close ? what are potential issues of each approach ?

like image 498
drus Avatar asked Dec 04 '25 11:12

drus


1 Answers

You can do either, but redirecting to /dev/null is safer and easier.

If you choose to close, you must make sure that any external programs or libraries you invoke still work when stdin/stdout/stderr is closed. Libraries and frameworks differ in how they handle this:

  • Shell scripts may abort or misbehave as echo unexpectedly returns non-success.
  • Python programs will see an arbitrary print statement fail with exceptions when the underlying buffer is written.
  • Ruby will just ignore it.

Even if your invoked programs or libraries normally doesn't print anything, you don't know what kind of conditional logging they do and how they handle failures there.

Unless all the code you run is known to handle not having standard i/o, it's better to just redirect.

like image 139
that other guy Avatar answered Dec 07 '25 01:12

that other guy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!