note 18942 rejected from ref.exec by didou

From: Date: Sun, 03 Aug 2003 10:23:44 +0000
Subject: note 18942 rejected from ref.exec by didou
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-53252@lists.php.net to get a copy of this message
Note Submitter: pvm@nworks.com ---- // If you need to get both the exit status and the return value of // exec it seems PHP's exec command is broken - at least on my // system. It does not return the exit status of the process // reliably, but always -1... Here is a workaround... // I'm running php v. 4.0.4pl1 on Linux SuSE 7.2 (from command line // and/or under apache) // Here is an example of the broken stuff in exec: // This next should work: $lines=array();$errco=0; $result = exec("ls -l /tmp 2>&1",$lines,$errco); echo "Errco: " . $errco . "\n"; echo "Result: " . $result . "\n\n"; // and this shouldn't (there is no such file as /tm $lines=array();$errco=0; $result = exec("ls -l /tm 2>&1",$lines,$errco); echo "FailErrco: " . $errco . "\n"; echo "FailResult: " . $result . "\n\n"; /* This outputs: Errco: -1 Result: -rw-r--r-- 1 root root 9670 Dec 21 18:27 xwlog FailErrco: -1 FailResult: ls: /tm: No such file or directory And the errco is always -1. From the command line, $? is 0, then 1 but never -1... Hmm... */ // This function returns the status (more) reliably. There are many // commands that can break it. E.g. if $cmd doesn't finish with a // newline... If $cmd spawns a process that prints output // asynchronously (i.e. after the echo $?). There are probably many // more.. But if you know that command your calling (I wrote mine // myself), it can work... // It is called same way as exec... function myExec($_cmd, &$lines, &$errco) { $cmd = "$_cmd ; echo $?"; exec($cmd, $lines); // Get rid of the last errco line... $errco = (integer) array_pop($lines); if (count($lines) == 0) { return ""; } else { return $lines[count($lines) - 1]; } } // this should work $lines=array();$errco=0; $result = myExec("ls -l /tmp 2>&1",$lines,$errco); echo "myErrco: " . $errco . "\n"; echo "myResult: " . $result . "\n\n"; // and this shouldn't $lines=array();$errco=0; $result = myExec("ls -l /tm 2>&1",$lines,$errco); echo "myFailErrco: " . $errco . "\n"; echo "myFailResult: " . $result . "\n\n"; /* This outputs: myErrco: 0 myResult: -rw-r--r-- 1 root root 9670 Dec 21 18:27 xwlog myFailErrco: 1 myFailResult: ls: /tm: No such file or directory So now I can test for whether a command succeeded or failed... Hope it helps someone. */

« previous php.notes (#53252) next »