1

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?

Hersheezy
  • 356
  • 1
  • 16

1 Answers1

1

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 in logrotate (see man logrotate); and abandon your named pipe solution.

ramruma
  • 2,730
  • 1
  • 14
  • 8
  • for my case, if the pipe exists i want to remove it. yeah i missed the <> at the end of the while loop, sorry. for the scripts i am working with, i don't care if stdout and stderr go to the same place. i also wanted to avoid overhead of a disk copy in logrotate which is why i am trying this in the first place. archiving overhead should be mitigated with nice. are there any other reasons you don't like the script? – Hersheezy May 20 '12 at 08:41