简体   繁体   中英

Redirecting output in shell script from subprocess with simulated ctrl-c

I am working on a shell script, where it sets some parameters and calls a python script. Sometimes the python script hangs and when I press ctrl-c, it generates some error output. I am trying to write this to a file. When I execute the shell script and press ctrl-c, I get the output in the redirected file, but if I try to simulate the ctrl-c by sleeping for some time and killing the process, the output is not redirected to the file. I have used some examples from SO to do the sleep and terminate which works, but the output file doesn't have the error which I get from ctrl-c action manually.

I cannot change the python script that this script is executing, so I have to implement this in the calling script.

[ -z "$1" ] && echo "No environment argument supplied" && exit 1
. env_params.txt
. run_params.txt


echo "========================================================== RUN STARTED AT $B =========================================================="  >> $OUTFILE
echo "    " >> $OUTFILE

export RUN_COMMAND="$PYTHON_SCRIPT_LOC/pyscript.py PARAM1=VALUE1 PARAM2=VALU2 PAram3=value3"

echo "Run command from test.sh $RUN_COMMAND"    >> $OUTFILE
echo "    " >> $OUTFILE
echo "    " >> $OUTFILE
echo "========================================================== Running Python script =========================================================="  >> $OUTFILE

echo "Before python command"

###############################################
( python $RUN_COMMAND  >> $OUTFILE  2>&1  )  & pid=$!

   SLEEP_TIME=1m
   echo "before sleep - sleeping for $SLEEP_TIME $pid"
   ( sleep $SLEEP_TIME && kill -HUP $pid ) 2>/dev/null & watcher=$!
   if wait $pid 2>/dev/null; then
   echo "after sleep - sleeping for $SLEEP_TIME $pid"
      echo "your_command finished"
      pkill -HUP -P $watcher
      wait $watcher
   else
       echo "after sleep - sleeping for $SLEEP_TIME $pid"
       echo "your_command interrupted"
   fi

### also tried this - did not work either
### python $RUN_COMMAND  >> $OUTFILE  2>&1 &; (pythonPID=$! ; sleep 1m ;kill -s 2 $pythonPID) 
 .
 .

What changes do I need to make such that the output is written to the $OUTFILE when the process is killed in the script itself, rather than pressing ctrl-c on the terminal?

Probabelly you do not want to use SIGHUP (Hangup detected on controlling terminal or death of controlling process, but rather

SIGINT        2       Term    Interrupt from keyboard

for more info read man 7 signal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM