Search code examples
bashexecution

Bash - starting and killing processes


I need some advice on a "simple" bash script.

I want to start around 500 instances of a program "myprog", and kill all of them after x number of seconds

In short, I have a loop that starts the program in background, and after sleep x (number of seconds) pkill is called with the program name.

My questions are:

  1. How can I verify that after 10 seconds all 500 instances are running? ps and grep combination with counting or is there another way?

  2. How can I get a count of how many processes did the pkill (or similar kill functions) actually kill (so that there are not any processes that terminate before the actual timelimit)?

  3. How can one redirect the output of pkill(or similar kill functions) so that it doesn't output the killed process information, so that 500 lines of ./initializeTest: line 250: 7566 Terminated ./$myprog can be avoided. Redirecting to /dev/null didn't do the trick.


Solution

  • 1,2. Use pgrep. I don't remember off the top of my head whether pgrep has -c parameter, so you might need to pipe that to wc -l.

    3: that output is produced by your shell's job control. I think if you run that as a script (not in an interactive shell), there shouldn't be such an output. For an interactive shell, the are number of ways to turn that off, but they are shell-dependent, so refer to your shell's manual.