preload preload preload preload

Background Process or a Deamon Process using PHP

Process Control Functions (PCNTL)

Introduction

Process Control support in PHP implements the Unix style of process creation, program execution, signal handling and process termination. Process Control should not be enabled within a web server environment and unexpected results may happen if any Process Control functions are used within a web server environment.

Requirements

No external libraries are needed to build this extension.

Installation

Process Control support in PHP is not enabled by default. You have to compile the CGI or CLI version of PHP with –enable-pcntl configuration option when compiling PHP to enable Process Control support.

Examples

This example forks off a daemon process with a signal handler.

#!/usr/local/bin/php -q //Include the file php

<’?php’
declare(ticks=1);
$cmd = ‘php’;
$file = array(’parse.php’);
$pid = pcntl_fork();
if ($pid == -1)
{
die(”could not fork”);
}
else if ($pid)
{
echo “parent”;
exit(); // we are the parent
}
else
{
echo “Child”;
exit(); // we are the child
}
// detatch from the controlling terminal
if (posix_setsid() == -1)
{
echo $pid;
echo “\n”;
die(”could not detach from terminal\n”);
}

// setup signal handlers
pcntl_signal(SIGTERM, “sig_handler”);
pcntl_signal(SIGHUP, “sig_handler”);

// loop forever performing tasks
while (1)
{
// do something interesting here
pcntl_exec(’php’,’file.php’); // executes ‘file.php’ in the back ground.
echo “”;
// exit;

}
function sig_handler($signo)
{

switch ($signo)
{
case SIGTERM:
// handle shutdown tasks
echo “\nShutdown”;
exit;
break;
case SIGHUP:
// handle restart tasks
echo “restart”;
break;
default:
// handle all other signals
}

}

‘?>’

For more details Click here

  • Share/Bookmark
  • Leave a Reply

    * Required
    ** Your Email is never shared