Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute shell commands synchronously in PHP

Tags:

shell

php

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 completes then only second should being then third one and so on.. Currently I am using the following code to do this

exec ("php phpscript1.php ");
exec ("php phpscript2.php ");
exec ("php phpscript3.php ");
exec ("php phpscript4.php ");
exec ("php phpscript5.php ");

I think these scripts run asynchronously, any suggestion guys so that these scripts can be run synchronously.

like image 324
Rahul Avatar asked Oct 01 '11 16:10

Rahul


5 Answers

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.

like image 132
stivlo Avatar answered Nov 13 '22 04:11

stivlo


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 &");.

like image 21
Dennis Avatar answered Nov 13 '22 06:11

Dennis


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.

like image 5
Daniel Lopes Avatar answered Nov 13 '22 06:11

Daniel Lopes


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

like image 3
ChrisH Avatar answered Nov 13 '22 05:11

ChrisH


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.

like image 2
vinit agrawal Avatar answered Nov 13 '22 05:11

vinit agrawal