$! variable and redirection to command

Functions, Variables, String Operators, Command Substitution, Arrays, if/else, while/until, for, case, select, I/O Redirectors, String I/O, Process ID's, Job Control, trap, signals, subshells, debugging.,

$! variable and redirection to command

Postby msmucr » Sun Jul 25, 2010 4:04 am

Hello to all board members here,

i'm little bit stuck with one script thing, so I will be very happy, if have some ideas regarding this.
I would like to create simple wrapper to start program in background, pipe its output to syslog and create pidfile.
Basically something like this:

$command 2>&1 | logger -t $syslogtag ($!) &
echo $! > $pidfile

I'm using logger command for redirection to syslog, -t is syslog tag, so it will write something like "mydaemon (pid)" on every line of program output.
So far, so good. But obviously when I would like to write pidfile, value in $! variable is updated by pid of logger process.

I tried few things
- $_ variable normally holds, last argument of last command (so it should be "(pid)"), but it won't work for me.
- any subcommands for storing of command pid to some variable broke redirection or sending to background
- pid of subsequent command is usually incremented by one, so theoretically i could subtract one to get first pid, but it is controlled by OS and i can't rely on this.

Do you know some way, how to solve it?

Thank you

Michal Smucr
msmucr
 
Posts: 2
Joined: Sun Jul 25, 2010 3:34 am

Re: $! variable and redirection to command

Postby msmucr » Sun Jul 25, 2010 7:45 am

Hello,

it seems, that i got one trick.
I found on man page of bash, that jobs builtin ivocation:
jobs -p List only the process ID of the job’s process group leader.

I my case with backgrounded job, first command is process group leader, so
echo $(jobs -p) > $pidfile
works fine.

Best regards

Michal Smucr
msmucr
 
Posts: 2
Joined: Sun Jul 25, 2010 3:34 am


Return to Programming

Who is online

Users browsing this forum: No registered users and 1 guest