This doesn't answer the question directly, but I would question why I need to have a file with the pid
in the name. If it is simply a unique filename that you are looking for, then there are more robust ways to do this. Most Unices have a mktemp
command (unfortunately this is not POSIX though). Using GNU mktemp
, you could do:
tmp_file=$(mktemp --tmpdir=. log_XXXXXXXXXX)
program_a >"$tmp_file"
If you have to access the files at a later date, then it may be useful to include the date/time in the filename:
log_file=$(mktemp --tmpdir=. log_"$(date +%F_%T)".XXX)
program_a >"$log_file"
If you are looking to ensure that only one instance of a specific process is running, then on Linux you can use flock
:
(
flock -n 9 || { echo "program_a already running"; exit 1; }
program_a
) 9>/var/lock/program_a
Otherwise, if you are looking to have another program read the output of program_a
while it is still running, then using a file is surely a method of last resort. Much better to use a pipe or a named pipe as per orion's answer.