Disadvantages of using exec command in php script

1.6k views Asked by At

In PHP,

 I need to execute background tasks. So I have three choices to run script from 
 following commands:

 1)exec
 2)shell_exec
 3)passthru

 I randomly decided to use exec command in PHP.
 Because All of these have similar characteristics.

Now I want to know that Is there any disadvantage of exec() command which will run in background ? Actually I am not much aware about this command.

Is It make separate thread from main thread ? If yes then,Is there any way to clean up or suspend this background thread ?or it simply forget it after firing the command?

I am asking this because in my code there is need to run this script very fast one after one within moments. So Is it create any server load ?

EDIT : I am using exec command like this :

exec("/usr/bin/php /path/to/Notification.php >> /path/to/log_file.log 2>&1 &");

Please guide me on this.Any help will be appreciated.

2

There are 2 answers

5
ciruvan On

It depends entirely on the kind of call you make if exec() will wait for the command to finish or not. Of course, running a lot of background threads on a server could potentially create lots of CPU load.

Now, normally any command you run with exec() will NOT be run in background, that means your PHP script will wait until the command finishes executing. In order to have your commands run in background, you have to redirect its output stream and tell it explicitly to run in background by adding this to your command:

> /dev/null 2>/dev/null &

Of course the downside of this will be that you can never retrieve any results from your commands back to PHP. It will be fire and forget.

0
Donald On

for you redirect both standard output and error output to file, I don't think there are any problems whether you use exec or shell_exec or passthru here.

as far as I know these are their major diffrences

shell_exec(): return the whole standard out put (it would not show anything on the terminal)

exec(): the same whith shel_exec(), but it juset return the last line of standard output

passthru(): this is like to call the command, it would show the output on the terminal instead of returning it.