2012-08-08 64 views
0

嗨請原諒我,如果這看起來非常噁心我剛開始學習如何腳本。如何從管道獲取我的進程ID?

我想在65秒後終止v​​lc,無論發生什麼情況,但是如果它在 期間與源斷開連接,我想殺死它並用新的輸出文件名重新啓動它。

#!/bin/bash 

function record { 
    DATE=$(date "+%d%m%y%H%M%S%N"); 

    cvlc -vR rtsp://192.168.1.233 \ 
     --sout=file/mov:/var/www/continuous/%1/$DATE.mov 2>& 1 | 

    while read event; 
    do 
    PID=$! 
    lastevent=${event#*]} 
    if [ "$lastevent" == "live555 demux warning: no data received in 10s, eof ?" ]; 
    then 
     kill $PID 
     record 
    fi 
    done 
} 

record & 
sleep 65 
kill $PID 

麻煩是$!沒有得到正確的PID,所以我不能殺死它。我需要獲得vlc的pid。

回答

0

您的想法與$!是錯誤的。這裏使用pkill -P$$好多了。

例子:

cvlc -vR rtsp://192.168.1.233 \ 
    --sout=file/mov:/var/www/continuous/%1/$DATE.mov | while read event; do 
    lastevent=${event#*]} 
    if [ "$lastevent" == "live555 demux warning: no data received in 10s, eof ?" ]; 
    then 
    pkill -P$$ cvlc 
    fi 
done 

使用pkill -P$$ cvlc你會殺死cvlc這是由shell啓動。

0

$!只適用於那些放在後臺明確過程。

這裏所提出的KSH,其中|&都有不同的意義幾乎可以工作的語法: 它在後臺作爲共同的過程,這意味着把一個命令,你可以read從 共同加工與read -p event

0

也許你可以將cvlc的輸出寫入一個命名管道,然後將它踢到背景,以便使用$!可以獲得pid。然後,您從命名管道中讀取並且cvlc在您的時間限制結束時死亡。

# create the named pipe 
MYPIPE=/tmp/cvlc_pipe_$$ 
rm -f ${MYPIPE} # remove the named pipe in case it already exist 
mkfifo ${MYPIPE} 

function record { 
    DATE=$(date "+%d%m%y%H%M%S%N"); 

    # have cvlc write to the named pipe in the background, then get its pipe with $1 
    cvlc -vR rtsp://192.168.1.233 \ 
     --sout=file/mov:/var/www/continuous/%1/$DATE.mov > ${MYPIPE} 2>& 1 && 
    PID=$! 

    # read cvlc's output from the named pipe 
    exec 7<>${MYPIPE} 
    while read -u 7 event; 
    do 
    PID=$! 
    lastevent=${event#*]} 
    if [ "$lastevent" == "live555 demux warning: no data received in 10s, eof ?" ]; 
    then 
     kill $PID 
     record 
    fi 
    done 
    exec 7>&- 
} 

record & 
sleep 65 
kill $PID 
rm -f ${MYPIPE} # cleanup 
0

這是我使用的最終解決方案(該腳本的名稱是vlcrecorder)。

它獲取自己孩子的pid(pgrep),因爲該函數調用它自己必須循環通過子孫,孫輩等,直到找到vlc的pid在樹的底部。

謝謝幫助我的人。

#!/bin/bash 
function record { 
DATE=$(date "+%d%m%y%H%M%S%N"); 
cvlc -v -R rtsp://$1/$2 --sout=file/mov:/var/www/continuous/2/$DATE.mov |& 
while read event; 
do 
lastevent=${event#*]} 
echo $lastevent 
if [[ "$lastevent" == *"live555 demux warning: no data received in 10s, eof ?"* ]]; then 
sleep .1 
ppid=$(pgrep -P $$ -x vlcrecorder) 
vlcpid=$(pgrep -P $ppid -x vlc) 
until [ -z "$ppid" ]; do 
vlcppid=$vlcgppid 
vlcgppid=$ppid 
ppid=$(pgrep -P $ppid -x vlcrecorder) 
done 
vlcpid=$(pgrep -P $vlcppid -x vlc) 
kill $vlcpid 
record $1 $2 
fi 
done 
} 

record $1 $2 & 
sleep 65 
parentpid=$! 
until [ -z "$parentpid" ]; do 
gppid=$parentpid 
parentpid=$(pgrep -P $parentpid -x vlcrecorder) 
lastvlcpid=$(pgrep -P $gppid -x vlc) 
if [ -n "$lastvlcpid" ]; then 
kill $lastvlcpid 
fi 
done