The script will not kill the process at that particular time which you want to give it as an input as the script will run and die it will not wait for a specific time.
You can tickle this in two ways.
- Loop but again it will run in the foreground
- Cronjob
#!/bin/bash
EXIT_ON_KILL=true
read -p 'Process: ' name
read -p 'Timecontrol: ' timecontrol
while :
do
current_time=$(date +"%T")
echo $current_time "control "
current_time=$(echo $current_time | cut -d':' -f1-2)
if [ "${timecontrol}" == "${current_time}" ]
then
echo "killing process"
kill -9 $(ps -ef | grep $name | awk '{print $2}')
if [ $? -eq 0 ]; then
echo "Process killed having name $name and having $pid"
if [ $EXIT_ON_KILL == true ];then
exit 0
fi
else
echo "Failed to Kill process having name $name"
exit 1
fi
fi
sleep 2
done
awk '{print $2}'
this return PID
in ubuntu, you have to check-in Centos if it returns PID
if not then change it to awk '{print $5}'
So you can run with
./kill_process.sh
Process: node
Timecontrol: 00:21
With Cron job, you do not need to pass time, just pass the name of the process and the script will run on the specified time and will kill the process.
#!/bin/bash
EXIT_ON_KILL=true
p_name=$1
kill -9 $(ps -ef | grep $p_name | awk '{print $2}')
if [ $? -eq 0 ]; then
echo "Process killed having name $p_name and having $pid"
if [ $EXIT_ON_KILL == true ];then
exit 0
fi
else
echo "Failed to Kill process having name $p_name"
exit 1
fi
Create-cron-job-on-CentOS
0 0 * * * /path_to_script/kill_process.sh node
This will kill process every-day-at-midnight