doushan2311 2016-01-09 20:21
浏览 155
已采纳

如何生成脚本的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
  • 写回答

1条回答 默认 最新

  • dongqiao5573 2016-01-09 20:32
    关注

    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 &
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类