Results 1 to 4 of 4
Hi,
I understand that $! is the PID of a command. For example:
Code:
#!/bin/bash
myprogram &
echo "PID of myprogram is $!"
I'd like to send the output of ...
- 08-11-2010 #1Just Joined!
- Join Date
- Jun 2009
- Posts
- 20
[SOLVED] BASH: get PID of first command in pipe
Hi,
I understand that $! is the PID of a command. For example:
I'd like to send the output of "myprogram" to both console and to a log file using the "tee" command but I also want to store the PID of "myprogam". Something like this:Code:#!/bin/bash myprogram & echo "PID of myprogram is $!"
The problem is that $! is now the PID of "tee" rather than the PID of "myprogram". Any suggestions how to achieve what I need? Thanks.Code:#!/bin/bash myprogram | tee ./logfile & echo "PID of myprogram is $!"
- 08-11-2010 #2Just Joined!
- Join Date
- Feb 2009
- Location
- Southport, England
- Posts
- 31
I think you could just write something like this:
so the PID is saved at the end of the file. I guess this wouldn't work if it's an ongoing program.Code:#!/bin/bash myprogram > logfile MYPROGRAM_PID=$! echo "PID = $MYPROGRAM_PID" >> logfile echo "PID of myprogram is $MYPROGRAM_PID"
If it is a C program, you could include the header <unistd.h> and use the method getpid() and print that out first, so it is the first thing written to the log file.
- 08-12-2010 #3
Unfortunately, you can't really do this easily. One suggestion I saw was using named pipes:
This way, we don't need to directly pipe myprogram into tee, so we can insert code in the middle.Code:#!/bin/bash fifoname=/tmp/myfifo.$$ mkfifo "$fifoname" myprogram > "$fifoname" & echo "PID is $!" tee ./logfile < "$fifoname"
DISTRO=Arch
Registered Linux User #388732
- 08-12-2010 #4Just Joined!
- Join Date
- Jun 2009
- Posts
- 20
Fixed. Thanks for the suggestions. The named pipe works well. Repeated here with a few small modifications:
Code:#!/bin/bash FIFONAME=/tmp/myfifo.$$ rm -f $FIFONAME mkfifo $FIFONAME myprogram > $FIFONAME & MYPROGRAM_PID=$! cat $FIFONAME | tee ./logfile


