Find the answer to your Linux question:
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 ...
  1. #1
    Just 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:

    Code:
    #!/bin/bash
    myprogram &
    echo "PID of myprogram is $!"
    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 | tee ./logfile &
    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.

  2. #2
    Just Joined!
    Join Date
    Feb 2009
    Location
    Southport, England
    Posts
    31
    I think you could just write something like this:

    Code:
    #!/bin/bash
    myprogram > logfile
    MYPROGRAM_PID=$!
    echo "PID = $MYPROGRAM_PID" >> logfile
    echo "PID of myprogram is $MYPROGRAM_PID"
    so the PID is saved at the end of the file. I guess this wouldn't work if it's an ongoing program.

    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.

  3. #3
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    Unfortunately, you can't really do this easily. One suggestion I saw was using named pipes:
    Code:
    #!/bin/bash
    
    fifoname=/tmp/myfifo.$$
    mkfifo "$fifoname"
    
    myprogram > "$fifoname" &
    echo "PID is $!"
    
    tee ./logfile < "$fifoname"
    This way, we don't need to directly pipe myprogram into tee, so we can insert code in the middle.
    DISTRO=Arch
    Registered Linux User #388732

  4. #4
    Just 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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...