how to rotate nohup.out file without killing my application

Solution 1:

You should take a look at flog in combination with logrotate. If you pipe your application output through this you can then SIGHUP the flog process without having to kill your running application.

flog (file logger) is a program that reads input from STDIN and writes to a file.

If SIGHUP is received, the file will be reopened, allowing for log rotation [see logrotate(8) on RH.]

The log file will only be reopened if flog detects that rotation has occurred (ie, old file gone or inode changed). flog is extremly small (less than 500 bytes memory footprint.)

Solution 2:

Not sure if I'm too late on this. But for others who stumble upon this forum now, I didn't have to try out anything with flog or anything.

My job starts simply like this:

nohup <my process> &

This starts my job and starts appending to a nohup.out in that directory.

All I had to do was to setup a logrotate which usually comes with the distro and configure something like this in /etc/logrotate.conf

~/my abosolute path/nohup.out {
    size 1024k
    copytruncate
    rotate 100
    maxage 100
}

And it worked!! nohup.out was getting truncated while getting the new appends on the same file. The process didn't die either. And a new nohup.out like nohup.out-20190528 this was created.

Hope this helps.

Solution 3:

You cannot rotate it. You can truncate it with the command >nohup.out, which will delete all contents in the file.

You can copy the file first and then truncate it, if you need to save the output. But there is a small window for a race, where output can be written after you copied the file but before you truncated it. Any output written during that window will be forever lost.

Solution 4:

You can do something like this:

cp nohup.out nohup.out.save # save it somewhere
echo "" > nohup.out

You don't need to kill your app.

Solution 5:

You can't.

You can unlink the file (rm) but the data still has a footprint on the disk and will continue to be written to as long as there is an open file handle.

You can rename the file - but again this does not stop it being written to (but if you are starting background jobs regularly the newer ones will write to the same file).

Really you should explicitly redirect the output of the job to something designed to handle this (e.g. apache rotatelogs).