Created
December 21, 2015 14:45
-
-
Save maple-nishiyama/3766172f4b3eed393807 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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