I have this bash script:
#!/bin/bash
if [ "$#" -eq 4 ]
then
rep_origine="$1"
rep_dest="$2"
temps_exec="$3"
temps_refr="$4"
else
echo "Usage : $0 [files directory] [destination directory] [execution time$
exit 2
fi
cp -R "$rep_origine" "$rep_dest" &
cp_process="$!"
while [ "$cp_process" -eq "$!" ]
do
cp_process="$!"
sleep "$temps_exec"; kill -STOP "$cp_process"
sleep "$temps_refr"; kill -CONT "$cp_process"
done
I would like my loop to end when the cp command ends. Therefore, I put that when the last PID was not the same as the PID of cp, the loop should end but it does not work.
I don't see how to indicate that the loop should end when the cp command ends.
CodePudding user response:
I would use kill
with the non-harming signal 0
to check if the process is still alive:
while kill -0 $cp_process 2>/dev/null
do
# work indicator:
echo -n '.'
sleep 1
done
If the purpose is to temporarilly stop the process in the loop:
while kill -STOP $cp_process 2>/dev/null
do
# do work while the process is stopped here
kill -CONT $cp_process
# give the process execution time:
sleep $temps_exec
done
CodePudding user response:
Not asked for, but the brackets in your usage message symbolize optional parameters, while you check for strictly 4 arguments.
Linux has a timeout program, to stop a process, which does not finish in a given time - maybe that's something for you.
#!/bin/bash
if [ "$#" -eq 4 ]
then
rep_origine="$1"
rep_dest="$2"
temps_exec="$3"
temps_refr="$4"
else
echo "Usage : $0 source_dir destination_dir execution_time temps_refr
exit 2
fi
timeout temps_exec cp -R "$rep_origine" "$rep_dest"
See man timeout
for further details.
CodePudding user response:
You can simply use ps and grep in this scenario to check if the process is running or not,
Ex:
#!/bin/bash
if [ "$#" -eq 4 ]
then
rep_origine="$1"
rep_dest="$2"
temps_exec="$3"
temps_refr="$4"
else
echo "Usage : $0 [files directory] [destination directory] [execution time$ "
exit 2
fi
cp -R "$rep_origine" "$rep_dest" &
cp_process="$!"
# check if the process is still running or not
while true; do
check=$(ps -ef | grep -w $cp_process | grep -v grep | wc -l)
if [ $check -ge "1" ]; then
echo "process $cp_process is still running"
else
echo "Process $cp_process has been completed"
break
fi
sleep 1
done