LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Started programs with one script. Want to kill them with another (https://www.linuxquestions.org/questions/programming-9/started-programs-with-one-script-want-to-kill-them-with-another-841786/)

halfpower 11-01-2010 06:51 PM

Started programs with one script. Want to kill them with another
 
I started several programs with the following script:
Code:

front_end1 input1_a &
sleep 4
program2 input2_a &
program2 input2_b &
program2 input2_c &
program5 input5_a &

program6 &

I would like to be able to shut them all down as well. Is there a way to do this with a second script? I don't know how to do this because the second script would not know the PIDs. Is there a way I can do all of this with just one script?

vamped 11-01-2010 11:41 PM

killall
 
You can kill programs by name as well as by pids. See man killall.

corp769 11-01-2010 11:47 PM

You can also use the following:

kill `ps aux | grep PROGRAM | awk "${2}"`

Most likely, I jacked up the quotation marks because I am at work and am using a *gag* windows machine.....so just fix the awk command up and there you go!

Dark_Helmet 11-02-2010 12:45 AM

Assuming that you're using bash, you're looking for the "jobs" builtin command. For instance:
Code:

#!/bin/bash

AWK="/usr/bin/awk"
DU="/usr/bin/du"

${DU} -hs /home/username/temp &
${DU} -hs /home/username/Documents &
${DU} -hs /home/username/Downloads &

job_pids=$( jobs -l | ${AWK} '{print $2}' )
for job_pid in ${job_pids} ; do
  echo "job_pid = ${job_pid}"
done

exit 0

The jobs builtin will display information about each process spawned by the environment the shell script was using. Use the '-l' option to have the PID listed for each job. For more info, type man bash and search for "SHELL BUILTIN COMMANDS" (e.g., in the man page, press the forward slash '/', type 'SHELL BUILTIN COMMANDS', and press Enter). You will need to continue scrolling down for a while, but you'll get there.

When using the '-l' option, the PID is displayed in the second column (hence the awk command).

You can then save the PIDs to a file. Your other script can read the PIDs from that file, kill the PIDs listed, and then delete the PID file.


All times are GMT -5. The time now is 04:33 PM.