0

I'd like to start n threads of a script, each with their own process id.

I currently do this via cronjob like so:

* * * * *    php /path/to/script.php >> /log/script.log 2>&1
* * * * *    php /path/to/script.php >> /log/script.log 2>&1
* * * * *    php /path/to/script.php >> /log/script.log 2>&1

Each of these three threads all log to the same script.log, which pairs output with its pid.

How can I do the same without copy/paste from a script?

Would the following spawn each of these with a different pid (accessible from php's getmypid())? Or would they all share the same script-launcher.sh pid?

#!/bin/bash
# Let's call this `script-launcher.sh`
# Launch 3 threads at once with `script-launcher.sh 3`

N=${1-0}
for i in {1..$N}
do
   php /path/to/script.php >> /log/script.log 2>&1
done
Ryan
  • 14,682
  • 32
  • 106
  • 179
  • 1
    all running processes have a unique pid. – pvg Jan 09 '16 at 20:27
  • Do I understand you to say that, using the above example, `script-launcher.sh 100` would spawn 100 processes of `script.php`, each with their own `pid`? – Ryan Jan 09 '16 at 20:32
  • i think this can help you http://stackoverflow.com/questions/19543139/bash-script-processing-commands-in-parallel you want start more parallel process for your script right ? when you start a process he automatic take a pid. – Laurentiu Jan 09 '16 at 20:32
  • 1
    @Ryan absolutely. pid would be meaningless if each running process did not have a unique one. Processes can share things like, say, a parent pid, possibly file descriptors, other resources. But the pid is unique and invariant. – pvg Jan 09 '16 at 20:38

1 Answers1

1

Whenever you span a new process, the new process will gain a new pid. So in this case, each time your shell script spans an instance of php, each of those copies of php will have their own pid.

The {1..$N} syntax will not work, though, so you will need to change your script to

N=${1-0}
for i in $(seq 1 $N)
do
   php /path/to/script.php >> script.log 2>&1
done

Then, if you call your script as script-launcher.sh 42, you'll get 42 instances of PHP running.

To have your php script run in the background (asynchronously), instruct bash to so with &:

   php /path/to/script.php >> script.log 2>&1 &
jbafford
  • 5,528
  • 1
  • 24
  • 37
  • How can I run these asynchronously? It looks like each process in the loop first waits for the previous one to complete. – Ryan Jan 09 '16 at 21:56
  • 1
    @Ryan I updated the answer with how to do that. (Add a `&` at the end of the command.) – jbafford Jan 09 '16 at 22:05