From a33558a61efc244ad8c809748e6ee64413e3a217 Mon Sep 17 00:00:00 2001
From: Andrew Dolgov <fox@madoka.volgo-balt.ru>
Date: Mon, 2 Sep 2013 12:33:59 +0400
Subject: [PATCH] pass logfile to child tasks if locking is possible, lock
 logfile before writing, add kludge to prevent update_rss_feed unneeded
 debugging go into master logfile

---
 include/functions.php | 24 ++++++++++++++++++++++++
 include/rssfuncs.php  |  2 ++
 update_daemon2.php    |  3 ++-
 3 files changed, 28 insertions(+), 1 deletion(-)

diff --git a/include/functions.php b/include/functions.php
index 2d6716b81..8ede14a0b 100644
--- a/include/functions.php
+++ b/include/functions.php
@@ -139,6 +139,8 @@
 	 * @return void
 	 */
 	function _debug($msg, $show = true) {
+		if (defined('SUPPRESS_DEBUGGING'))
+			return false;
 
 		$ts = strftime("%H:%M:%S", time());
 		if (function_exists('posix_getpid')) {
@@ -153,7 +155,29 @@
 			$fp = fopen(LOGFILE, 'a+');
 
 			if ($fp) {
+				$locked = false;
+
+				if (function_exists("flock")) {
+					$tries = 0;
+
+					// try to lock logfile for writing
+					while ($tries < 5 && !$locked = flock($fp, LOCK_EX | LOCK_NB)) {
+						sleep(1);
+						++$tries;
+					}
+
+					if (!$locked) {
+						fclose($fp);
+						return;
+					}
+				}
+
 				fputs($fp, "[$ts] $msg\n");
+
+				if (function_exists("flock")) {
+					flock($fp, LOCK_UN);
+				}
+
 				fclose($fp);
 			}
 		}
diff --git a/include/rssfuncs.php b/include/rssfuncs.php
index 2bc30b5ce..7f6417759 100644
--- a/include/rssfuncs.php
+++ b/include/rssfuncs.php
@@ -194,6 +194,8 @@
 
 		$debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug'];
 
+		if (!$debug_enabled) define('SUPPRESS_DEBUGGING', true);
+
 		_debug("start", $debug_enabled);
 
 		$result = db_query("SELECT id,update_interval,auth_login,
diff --git a/update_daemon2.php b/update_daemon2.php
index 9d948a64d..e5bc55ee0 100755
--- a/update_daemon2.php
+++ b/update_daemon2.php
@@ -218,10 +218,11 @@
 					register_shutdown_function('task_shutdown');
 
 					$quiet = (isset($options["quiet"])) ? "--quiet" : "";
+					$log = function_exists("flock") && isset($options['log']) ? '--log '.$options['log'] : '';
 
 					$my_pid = posix_getpid();
 
-					passthru(PHP_EXECUTABLE . " update.php --daemon-loop $quiet --task $j --pidlock $my_pid");
+					passthru(PHP_EXECUTABLE . " update.php --daemon-loop $quiet $log --task $j --pidlock $my_pid");
 
 					sleep(1);
 
-- 
GitLab