2012-08-08 63 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