Skip to content

Instantly share code, notes, and snippets.

@maple-nishiyama
Created December 21, 2015 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maple-nishiyama/3766172f4b3eed393807 to your computer and use it in GitHub Desktop.
Save maple-nishiyama/3766172f4b3eed393807 to your computer and use it in GitHub Desktop.
<?php
// PHPのプロセスをデーモン状態にする
$pid = pcntl_fork();
if ($pid < 0) {
die("フォーク失敗\n");
} else if ($pid > 0) {
// 親プロセス
exit();
}
// 子プロセス
// 制御端末の切り離し
$sid = posix_setsid();
if ($sid < 0) {
die("セッションを生成できませんでした。\n");
}
// セッションリーダーでなくする
// 2回めの fork()
$pid2 = pcntl_fork();
if ($pid2 < 0) {
die("2回めのフォーク失敗\n");
} else if ($pid2 > 0) {
// 子プロセス
exit();
}
// 孫プロセス
// ルートディレクトリをカレントディレクトリへ
chdir("/");
// 標準入出力を閉じる
fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
// デーモンになった!
$fp = fopen('/Users/nishiyama/dev/AdventCalendar2015/daemon/daemon.log', 'w');
while (true) {
sleep(1);
fwrite($fp, "daemon process\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment