【问题标题】:If I have 2 php scripts in an sh file can I be sure that the second script will only start running after the first script has completed?如果我在 sh 文件中有 2 个 php 脚本,我可以确定第二个脚本只会在第一个脚本完成后开始运行吗?
【发布时间】:2011-07-07 20:18:57
【问题描述】:

如果我在一个 sh 文件中有 2 个 php 脚本并且我从命令行或从 cron 运行 sh 文件,我能否确定第二个脚本只会在第一个脚本完成后才开始运行?

在 test.sh 我有

php test1.php
php test2.php

然后我运行 test.sh。我可以确定在 test1.php 完成之前 test2.php 不会启动吗?

【问题讨论】:

    标签: php linux shell cron


    【解决方案1】:

    如果“test1.php”自己守护进程,那么“test2.php”可能会在前者终止之前执行。如果你想避免这种情况,你可以使用类似下面的东西:

    #!/usr/bin/env bash
    
    test1.php
    
    PIDLIST=$(ps axwww | fgrep -v grep | fgrep "test1.php" | awk '{ print $1 }')
    
    while [ ! -z "$PIDLIST" ]; do
        sleep 1
        PIDLIST=$(ps axwww | fgrep -v grep | fgrep "test1.php" | awk '{ print $1 }')
    done
    
    test2.php
    

    假设在任何给定时间,系统上只能运行一个 test1.php。

    【讨论】:

    • test1.php 并不需要做完整的守护进程;只需分叉并退出就足够了。 (守护进程经过一些不影响结果的额外工作;解释大部分是正确的,只是过于具体。)但是 +1 指出了分叉的可能性。
    【解决方案2】:

    你得到了你所得到的 - 除非 test1.php 完成,否则 php 不会退出,然后它将启动 test2.php。但是,这不适用于 fastcgi 之类的任何包装器。

    您可以使用许多并行流程管理工具。请参阅我在 SF 的问题 - https://serverfault.com/questions/259491/shell-script-run-a-batch-of-n-commands-in-parallel-wait-for-all-to-finish-run

    【讨论】:

      【解决方案3】:

      test1.php 中设置一些变量并将该变量发送到test2.php 检查test2.php 中的变量值如果未设置则执行exit()

      【讨论】:

        【解决方案4】:

        如果我无知(初学者 sh 用户),请原谅我,但您不能使用 && 分隔命令,以便仅在第一个命令返回 0 值(成功)后执行第二个命令吗?

        (command1) && (command2);

        编辑:或使用 ||如果命令 1 返回非零,则运行命令 2

        【讨论】:

          猜你喜欢
          • 2023-02-08
          • 2021-01-15
          • 1970-01-01
          • 2023-03-10
          • 2011-10-10
          • 2015-05-05
          • 2020-05-18
          • 2011-11-18
          • 1970-01-01
          相关资源
          最近更新 更多