PHP fork process - getting child output in parent

前端 未结 3 1978
忘掉有多难
忘掉有多难 2021-01-20 03:44

I want to achieve the following:

Initialize an array. Child process adds some elements to the array. Parent process adds some elements to the array. Finally before

相关标签:
3条回答
  • 2021-01-20 04:12

    Forked children will gain their own dedicated copy of their memory space as soon as they write anywhere to it - this is "copy-on-write". While shmop does provide access to a common memory location, the actual PHP variables and whatnot defined in the script are NOT shared between the children.

    Doing $x = 7; in one child will not make the $x in the other children also become 7. Each child will have its own dedicated $x that is completely independent of everyone else's copy.

    a local domain socket is easiest. have the parent open one with fsockopen for each child immediately before the fork. that way you can have one comm channel per child: http://php.net/manual/en/transports.unix.php and http://php.net/manual/en/transports.unix.php.

    You could also shared memory, or open a bi-directional communications channel between the two processes and build a little api to send data back and forth.

    As long as father and children know the key/keys of the shared memory segment is ok to do a shmop_open before pcnlt_fork. But remember that pcnlt_fork returns 0 in the child's process and -1 on failure to create the child (check your code near the comment /confusion/). The father will have in $pid the PID of the child process just created.

    Check it here:

    http://php.net/manual/es/function.pcntl-fork.php

    0 讨论(0)
  • 2021-01-20 04:14

    (sorry for crossposting)

    I suggest a look at socket_create_pair().

    In the PHP manual is a very short & easy example of interprocess communication (IPC) between a fork()-parent and the child.

    And using serialize() und unserialize() You could even transfer complex data types like arrays...

    0 讨论(0)
  • 2021-01-20 04:20

    The child's code is missing the print_r() statement.

    The parent won't print what the child added to values, as the addition was done after the child process had been fork()ed off, and with this it had gotten its own copy of the prcoess' memory.

    From the fork-tag's excerpt (emphasis by me):

    The fork() function is the Unix/Linux/POSIX way of creating a new process by duplicating the calling process.

    This behaviour of forking is different from threading where all threads share the same address space.

    0 讨论(0)
提交回复
热议问题