]> git.wh0rd.org - tt-rss.git/blame - update_daemon2.php
update_daemon2: fix locking
[tt-rss.git] / update_daemon2.php
CommitLineData
02008cb1
AD
1#!/usr/bin/php
2<?php
3 // This is an experimental multiprocess update daemon
4 // It consists of the master server (this file) and
5 // client batch script (update_daemon2_client.php) which
6 // should only be run by the server process
7
8 declare(ticks = 1);
9
6a69e61f
AD
10 require_once "config.php";
11 require_once "functions.php";
02008cb1
AD
12
13 define('MAX_JOBS', 2);
14 define('CLIENT_PROCESS', './update_daemon2_client.php SRV_RUN_OK');
15 define('SPAWN_INTERVAL', DAEMON_SLEEP_INTERVAL);
16
17 $running_jobs = 0;
18 $last_checkpoint = -1;
19
20 function sigchld_handler($signal) {
21 global $running_jobs;
22 if ($running_jobs > 0) $running_jobs--;
23 print posix_getpid() . ": SIGCHLD received, jobs left: $running_jobs\n";
24 pcntl_waitpid(-1, $status, WNOHANG);
25 }
26
6a69e61f
AD
27 function sigint_handler() {
28 unlink(LOCK_DIRECTORY . "/update_daemon.lock");
29 die("Received SIGINT. Exiting.\n");
30 }
31
02008cb1 32 pcntl_signal(SIGCHLD, 'sigchld_handler');
6a69e61f
AD
33 pcntl_signal(SIGINT, 'sigint_handler');
34
884c0a36
AD
35 if (file_is_locked("update_daemon.lock")) {
36 die("error: Can't create lockfile. ".
6a69e61f
AD
37 "Maybe another daemon is already running.\n");
38 }
02008cb1 39
884c0a36
AD
40 if (!pcntl_fork()) {
41 $lock_handle = make_lockfile("update_daemon.lock");
42
43 if (!$lock_handle) {
44 die("error: Can't create lockfile. ".
45 "Maybe another daemon is already running.\n");
46 }
47
48 while (true) { sleep(100); }
49 }
50
02008cb1
AD
51 while (true) {
52
53 $next_spawn = $last_checkpoint + SPAWN_INTERVAL - time();
54
ce1aa9b7
AD
55 if ($next_spawn % 10 == 0) {
56 print "[MASTER] active jobs: $running_jobs, next spawn at $next_spawn sec\n";
57 }
02008cb1
AD
58
59 if ($last_checkpoint + SPAWN_INTERVAL < time()) {
60
61 for ($j = $running_jobs; $j < MAX_JOBS; $j++) {
62 print "[MASTER] spawning client $j...";
63 $pid = pcntl_fork();
64 if ($pid == -1) {
65 die("fork failed!\n");
66 } else if ($pid) {
67 $running_jobs++;
68 print "OK [$running_jobs]\n";
69 } else {
70 pcntl_signal(SIGCHLD, SIG_IGN);
6a69e61f 71 pcntl_signal(SIGINT, SIG_DFL);
02008cb1
AD
72 passthru(CLIENT_PROCESS);
73 exit(0);
74 }
75 }
76 $last_checkpoint = time();
77 }
78 sleep(1);
79 }
80
81?>