如何生成脚本的n个线程,每个线程都有自己的进程ID?
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
我想启动脚本的 n em>个线程,每个线程都有自己的进程 id。 p>
我目前通过 这三个线程中的每一个都记录到相同的 如果没有从脚本中复制/粘贴,我怎么能这样做呢? p>
会不会 以下使用不同的 cronjob code>这样做: p>
* * * * * 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
code> pre>
script.log code>,其中 使用
pid code>对输出进行输出。 p>
pid code>(可从
php code>的
getmypid() code>访问)生成每个这些? 或者他们都会共享相同的
script-launcher.sh code> pid? p>
#!/ bin / bash
#让我们称之为`脚本 - launcher.sh`
#在{1 .. $ N}
do
php / path中使用`script-launcher.sh 3`
N = $ {1-0}
for i一次启动3个线程 /to/script.php>> /log/script.log 2>& 1
done
code> pre>
div>
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 &