Ruhi Singh
Ruhi Singh

Reputation: 186

How to find if command executed in exec command fails?

I need to know that If I call a php script execution command through exec command and the script execution fails due to any reason say "file not found" , then how can I find it out. I have following command :

    $cmd="php testfile.php" ;
    $outputfile="testoutput.txt";
    exec(sprintf("%s > %s 2>&1 & echo $!", $cmd, $outputfile),$pidArr, $status);

exec command return -1 in case of error but in this case exec is executing successfully ie $status is coming 0 in my case but the "php testfile.php" command is failing, the output is getting in testoutput.txt. But I need to know the way so that I can identify it after exec if the command is failed. I could think of the option of reading testoutput.txt and grep for fail or error word, but I dont think it is reliable.

Thanks in advance!

Upvotes: 1

Views: 4602

Answers (2)

Chelsea Urquhart
Chelsea Urquhart

Reputation: 1428

http://php.net/manual/en/function.exec.php

exec(sprintf("%s > %s 2>&1 & echo $!", $cmd, $outputfile),$pidArr, $status);

$status=0 if no errors, > 0 if errors

Upvotes: 1

liyakat
liyakat

Reputation: 11853

You can receive the output result of the exec function by passing an optional second parameter:

So you could execute the exec() with that 3rd arg, then check if it is non-zero for an error condition.

exec("blah blah blah", $output, $result); 
if($result > 0) 
{ 
   die('error message here'); 
}  

If you don't find the error through that second parameter, you can search for the error log of apache, for example in Ubuntu Server 12.10 through the command $ tail /var/log/apache2/error.log

let me know if i can help you more.

Upvotes: 2

Related Questions