Search code examples
phpmacoscommand-line-interfacepcntl

PHP: pcntl_fork() on the OSX command line


I have a Macbook Pro running OSX Yosemite. I am trying to run a simple PHP script using pcntl_fork() on the command line (command: php pcntl.php):

<?php
    $pid = pcntl_fork();

    switch($pid) {
        case -1:
            print "Could not fork!\n";
            exit;
        case 0:
            print "In child!\n";
            break;
        default:
            print "In parent!\n";
    }
?>

The response is this:

Fatal error: Call to undefined function pcntl_fork() in
/Users/grant/Desktop/test/pcntl.php on line 2

I've seen numerous articles that show you how to install pcntl if you are running mamp, but if you are simply using terminal, how would you go about installing pcntl? If this is not possible on the command line, is there something similar in PHP that does work?


Solution

  • In case of native CLI you should proceed the same way as in case of MAMP. The only difference is that you should add support to native php and not to MAMP's one.

    Yosemite's php doesn't have pcntl support. Following command returns no output:

    $ php -i | grep pcntl
    

    Verify your php version:

    $ php -v
      PHP 5.5.20 (cli) (built: Feb 25 2015 23:30:53)
    

    Download and build pcntl module:

    $ wget http://php.net/distributions/php-5.5.20.tar.xz
    $ tar xf php-5.5.20.tar.xz
    $ cd php-5.5.20
    $ cd ext/pcntl/
    $ phpize
    $ ./configure
    $ make
    

    Copy module to extensions folder:

    $ sudo cp modules/pcntl.so /usr/lib/php/extensions/no-debug-non-zts-20121212/
    

    Edit php.ini configuration file:

    $ sudo vi /etc/php.ini
    

    And add extension=pcntl.so line in Dynamic Extensions section, e.g.:

    ;;;;;;;;;;;;;;;;;;;;;;
    ; Dynamic Extensions ;
    ;;;;;;;;;;;;;;;;;;;;;;
    
    ; If you wish to have an extension loaded automatically, use the following
    ; syntax:
    ;
    ;   extension=modulename.extension
    ;
    ; For example, on Windows:
    ;
    ;   extension=msql.dll
    ;
    ; ... or under UNIX:
    ;
    ;   extension=msql.so
    ;
    ; ... or with a path:
    ;
    ;   extension=/path/to/extension/msql.so
    ;
    ; If you only provide the name of the extension, PHP will look for it in its
    ; default extension directory.
    
    extension=pcntl.so
    

    Verify pcntl support again (support enabled this time):

    $ php -i | grep pcntl
      pcntl
      pcntl support => enabled
    

    Running your test script:

    $ php -f test.php
      In parent!
      In child!