Suppose I have some kind of $ models array like this:

array(5) { [0]=> array(1) { ["props"]=> array(2) { [0]=> string(5) "prop0" [1]=> string(5) "prop1" } } [1]=> array(1) { ["props"]=> array(2) { [0]=> string(5) "prop2" [1]=> string(5) "prop3" } } [2]=> array(1) { ["props"]=> array(2) { [0]=> string(5) "prop4" [1]=> string(5) "prop5" } } ... } 

I work with this array using the following method:

 private function getPropData($name, $filename = self::FILE) { exec('render ' . $name); if (!file_exists($filename)) echo 'Not exist' . PHP_EOL; $handle = fopen($filename, 'rb'); if ($handle === false) throw new Exception('Fail'); $contents = json_decode(fread($handle, filesize($filename))); fclose($handle); if (empty($contents)) { throw new Exception('File is empty'); } return $contents; } 

I run this method in a loop for each prop ( prop1 , prop2 ...), and the value of prop is passed to the $name variable. exec - executes the render prop1 (example for prop1 ), which writes to the file specified in self::FILE (for example, /var/www/rendered/file.txt ), with the w flag (each time data is overwritten) data in the format JSON Further in this method the file is simply opened, the data is decoded and returned. The execution of the render program for each call takes approximately 5 seconds. The problem is that when I run the whole thing in a loop for each prop , then for some exec values ​​it does not start or starts, the file is created, but the "File is empty" exception is thrown. Perhaps the render program does not have time to finish its work and php already trying to open the file, but everything seems to be happening consistently. Moreover, if I sit and manually write in the console in the console

 render prop1 render prop2 ... 

then the /var/www/rendered/file.txt file will correctly overwrite for each prop . Help me figure out what's wrong.

  • Probably an error in the render command, it does not write data to the file. Do not use the outdated functions of working with files without a good reason. In php5 there are functions file_get_contents and file_put_contents, which cover 99% of the needs of developers, and it’s also harder to make a mistake with them. - Marsel Arduanov
  • but when I manually set the render command for each prop, then everything works, the data is written to the file with each command. - code
  • @MarselArduanov Please post your comment as a response. - Nicolas Chabanovsky

2 answers 2

Probably an error in the render command. it does not write data to the file.

Do not use the outdated functions of working with files without a good reason. In php5 there are functions file_get_contents and file_put_contents, which cover 99% of the needs of developers, and it’s also harder to make a mistake with them.

    When you run exec , a process is created that is not related to the execution of your script, and therefore will not wait for it, it is possible to overlay logic between processes in a cycle