I have a lot of code I need to daemonize that prints to standard out. I am thinking of using the following shell script to create a named pipe so I can nohup a process while redirecting its output to the pipe.
#!/bin/bash ###############3 # creates a pipe with name pipename that will redirect to filename and rotate logs on C-c ###############3 if [ $# -ne 2 ]; then echo "USAGE: ./$0 pipename filename" exit -1 fi pipename=$1; if [ -p $pipename ]; then rm $pipename; fi origname=$2.log filename=$2 rename() { newfilename="$origname-`date +%s`" mv $origname $newfilename nohup nice -n 20 tar -czvf $newfilename.tar.gz $newfilename & trap rename 2 } mkfifo $pipename trap rename 2 while [ 1 -eq 1 ] do read input echo $input >> $origname done $pipename
Then I could start a process in the following way:
nohup myprog.py > namedpipe 2>&1 &
After it is started I would set up a cron job to send it a signal for rotation.
Is this script robust / efficient?
Best Answer
No.
If namedpipe already exists, print a warning and stop rather than simply delete it: what happens to the script that was using it? Look at existing scripts in
/etc/init.d
. Look at start-stop-daemon on Debian and Ubuntu (or any Debian-derived distro).Error messages should go to stderr, not stdout. There is a missing input redirection at the end. Tar adds unneeded overhead: just gzip the file.
And so on.
But in any case, all this is unnecessary to add log rotation to scripts started with nohup: just use the
copytruncate
option inlogrotate
(seeman logrotate
); and abandon your named pipe solution.