LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   lsof output not redirecting in a cronjob (https://www.linuxquestions.org/questions/linux-newbie-8/lsof-output-not-redirecting-in-a-cronjob-905272/)

threezerous 09-27-2011 02:07 PM

lsof output not redirecting in a cronjob
 
When I run this command as root, I get the correct output of all open files opened by by the process 5018

lsof -p 5018 > lsof_output.txt

However, when I put this in a cron job

56 13 * * * lsof -p 5018 2>&1 > /root/lsof_output.txt

no output is written to lsof_output.txt

I confirmed that the job runs, by actually deleting the file before the scheduled time. A new empty file is created with no content. The process 5018 is active at the time the cron job runs.

What am I missing?

Thanks in advance.

anomie 09-27-2011 02:41 PM

Try using the fully-qualified path to lsof(8). If you're not sure where it is, find out with:
Code:

# whereis lsof

threezerous 09-27-2011 03:01 PM

Thank you....that helped

unSpawn 09-27-2011 05:39 PM

Quote:

Originally Posted by threezerous (Post 4483722)
What am I missing?

...I'd say you're missing more than just the cron PATH inclusion:
- when listing things always look for switches like "-n" as they may speed up processing by not translating. For lsof it's "-Pwln".
- using "-p $PID" is not extensible. Could pick up the actual PID with for example something like 'pgrep' ('man pgrep').
- root is no ordinary user and as such you shouldn't use it for write ops: use /tmp (or /dev/shm) for scratch files, /var/log for log files or 'logger' to pipe output into say syslog. If you're writing temporary files try using 'mktemp'.

Put together:
Code:

#!/bin/bash --
umask 0027; TEMPFILE=`mktemp /dev/shm/lsof.XXXXXXXXXXXX` && {
 pgrep sendmail 2>/dev/null|xargs -iP /usr/sbin/lsof -Pwlnp 'P' > "${TEMPFILE:/tmp/$$}" 2>&1
 [ -s "${TEMPFILE:/tmp/$$}" ] && install -o root -g root -m 0640 "${TEMPFILE:/tmp/$$}" "/var/log/lsof_$(/bin/date +'%Y%m%d').log"
 rm -f "${TEMPFILE:/tmp/$$}"
}; exit 0


Code:

function help() { echo "Bash scripting guides:
http://www.tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html
http://www.tldp.org/LDP/Bash-Beginners-Guide/html/index.html
http://www.gnu.org/software/bash/manual/html_node/index.html
http://www.grymoire.com/Unix/Sh.html
http://www.tldp.org/LDP/abs/html/
http://wooledge.org/mywiki/BashFAQ?action=show&redirect=BashFaq
http://wooledge.org/mywiki/BashPitfalls"; }



All times are GMT -5. The time now is 07:14 PM.