Stop avconv Bash script on user input and continue loop

こ雲淡風輕ζ 提交于 2019-12-08 10:50:24

问题


Basically (hopefully) I want to record a video stream from a webcam and save it in a specific directory, then kill that when a user inputs some numbers. I'm not explaining this well so here's what I'm doing currently:

#!/bin/bash

while true
do

TIMESTAMP=$(date +"%Y.%m.%d_%H.%M")

read -p "Enter your number here: " YOURNUMBER

echo -e "Saving video stream:"

mkdir /home/$USER/orders/$YOURNUMBER

avconv -f video4linux2 -r 3 -fs 52428800 -i /dev/video0 /home/$USER/orders/$YOURNUMBER/$TIMESTAMP-$YOURNUMBER.avi

echo -e "Video complete!"

done

So I want to stop the recording and start a new on in the new $YOURNUMBER folder. Any ideas? (Quite new to this..be patient!)

Update:

Thanks to @TrueY

Updated script (don't need to mkdir really so taken that out):

CPID=0
while :; do
  read -p "Enter your number here: " YOURNUMBER
  [ $CPID -ne 0 ] && kill -INT $CPID
  TIMESTAMP=$(date +"%Y.%m.%d_%H.%M")
  avconv -f video4linux2 -r 3 -fs 52428800 -i /dev/video0 /home/$USER/orders/$YOURNUMBER[packed-$TIMESTAMP].avi > /dev/null 2>&1 &
  CPID=$!
done

Only trouble is that I (or the end user) has to enter the number twice before it starts recording it again..


回答1:


UPDATED

Try something like this (OP's code modified a little bit):

#!/usr/bin/bash

stop() { [ $CPID -ne 0 ] && kill -INT $CPID && wait $CPID && echo "Killed $CPID"; }

trap "stop; exit" INT

CPID=0
while :; do
  read -p "Enter your number here: " YOURNUMBER
  stop
  [ "$YOURNUMBER" == quit ] && break;
  TIMESTAMP=$(date +"%Y.%m.%d_%H.%M")
  avconv -f video4linux2 -r 3 -fs 52428800 -i /dev/video0 /home/$USER/orders/$YOURNUMBER/$TIMESTAMP-$YOURNUMBER.avi&
  CPID=$!
  echo -e "Video complete!"
done

This starts avconv in the background so the user can enter a new number. Maybe the stdout and stderr of avconv should be redirected to a log file or to /dev/null. Also it should be tested which signal stops avconv gracefully. -INT is equivalent to ctrl+c. It it does not work, try -HUP, -TERM or even -KILL if nothing else helps. Maybe You should implement a trap to catch INT signals to kill the last avconv it ctrl+c is pressed.



来源:https://stackoverflow.com/questions/17567490/stop-avconv-bash-script-on-user-input-and-continue-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!