简体   繁体   中英

Linux bash script with stop/start option

I developed a script that find the number of running thread by given PID (as argument). we can run it once and everything work perfect. but, for our need i must make it to run with start and stop option. means, until i'm not make it stop the script week logging the thread number. i tried to do so in my code below but seems no luck

PID=$1
Command=$2
scriptPID=`echo $$`
#going to check if arguments were supplied if not using the defaults. if only one argument supplied then aborting.
if [[ $PID -eq 0 ]]
        then
                 echo -e "\n[ERROR]: No PID was provided. please provide PID as argument.\n"
                 exit 1
fi
initCommand(){
       #local Command="$2";
       case $Command in
              start)
                     start "true"
                     ;;
              stop)
                     stop -f "true"
                                        ;;
       esac
}
start(){
#going redirect stout & stderr to log file
echo "starting"
echo "script PID $scriptPID"
exec 1>>pidThreadNumber.log 2>&1
while (true); do
runningThreads=`ps huH p $PID | wc -l`
date;
echo "-------------------------------"
echo -e "Number of running threads: "$runningThreads"\n\n" 
sleep 2
done
}
stop()
{
kill -9 $scriptPID
}
initCommand $Command

Thank you all for the help

It doesn't work because each time you execute the command you have a different process hence a different scriptPID. Hence you could either:

  • store the pid of the process in a file where you find it again and use it to kill it

  • search for the process to be killed by looking at all processes with ps and choosing the right one by its name.

added after OP clarification. You can implement a "daemon mode" of your script. One way to do it is to accept a -d option and in that case run the script itself in background (without -d !) write the IP of the child to a file and then exit. Then you can read the IP from the file to later stop the child.

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