How to execute shell commands synchronously in PHP

后端 未结 5 894
小鲜肉
小鲜肉 2020-12-01 20:36

I need to run multiple scripts(5 scripts) via cmd, I want to make sure unless and until the first script finishes the second should not initiate. Thus after first script com

相关标签:
5条回答
  • 2020-12-01 21:10

    Both exec and system wait for the script to execute unless you don't fork.

    Check.php

    <?php
        echo "here ".__LINE__."\n";
        exec ("php phpscript1.php");
        echo "here ".__LINE__."\n";
        system("php phpscript2.php");
        echo "here ".__LINE__."\n";
    ?>
    

    phpscript1.php

    <?php
    echo "=================phpscript1.php\n";
    sleep(5);
    ?>
    

    phpscript2.php

     <?php
        echo "=================phpscript2.php\n";
        sleep(5);
        ?>
    

    Check.php execute script1 for 5 seconds then display next line number and then execute script2 by printing the next line.

    0 讨论(0)
  • 2020-12-01 21:13

    If I'm getting you right, you're executing php scripts from inside a php script.

    Normally, php waits for the execution of the exec ("php phpscript1.php"); to finish before processing the next line.

    To avoid this, just redirect the output to /dev/null or a file and run it in background.

    For example: exec ("php phpscript1.php >/dev/null 2>&1 &");.

    0 讨论(0)
  • 2020-12-01 21:14

    PHP exec will wait until the execution of the called program is finished, before processing the next line, unless you use & at the end of the string to run the program in background.

    0 讨论(0)
  • 2020-12-01 21:17

    In my opinion, it would be better to run cronjobs. They will execute synchronously. If the task is "on-the-fly", you could execute the command to add this cronjob. More information about cronjobs: http://unixgeeks.org/security/newbie/unix/cron-1.html

    http://service.futurequest.net/index.php?_m=knowledgebase&_a=viewarticle&kbarticleid=30

    0 讨论(0)
  • 2020-12-01 21:28

    Check out the exec function syntax on php.net. You will see that exec does not run anything asynchronously by default.

    exec has two other parameters. The third one, return_var can give you a hint if the script ran successfully or any exception was fired. You can use that variable to check if you can run the succeeding scripts.

    Test it and let us know if it works for you.

    0 讨论(0)
提交回复
热议问题