Tips&Tricks

How to run a program as daemon without any output

terminal

Each program has a set of file descriptors. It’s like an open stream from / to file. On start program has 3 descriptors: standard input (stdin), standard output (stdout) and standard error (stderr). They has numbers: from 0 to 2.

Standard input is used for reading input data from the user (from the terminal). Standard output is used for printing info to the user / terminal, or to another program (for example through the pipe). And standard error is an output for warnings end error messages.

If we want to disable printing to the terminal, we can redirect the output stream. We can do this by defining file for the output: some_program > /path/to/file.txt . This is short from some_program 1> /path/to/file.txt. “1” – is a number of the stdout stream.

But it’s dirty to create a file for each run. We have a global system file for this – /dev/null. It’s a file where you can put everything and on one can read it (like an utilizer).

Next we should handle the standard error file descriptor. Like we did it before, we’ll redirect it to another stream. For example – we can redirect it to the standard output like this: some_program 2>&1. “2” is a number for stderr stream. And we can to access a file descriptor by adding “&” before its number.

Now we don’t have any messages in the terminal while program works. But it locks the terminal. We need to detach the program from the terminal. We can do it by appending & symbol to the command. It’s a Bash syntax.

And finally…

Redirect stderr to output and put them all to /dev/null (nothing). Also detach the process from the terminal:

some_program 2>&1 >> /dev/null &