user2548436
user2548436

Reputation: 925

Php proc_open - save process handle to a file and retrieve it

I use the following code to open a process with proc_open, and to save the handle and the pipes to a file:

    $command = "COMMAND_TO_EXECUTE";

    $descriptors = array(
        0 => array("pipe", "r"), // stdin is a pipe that the child will read from
        1 => array("pipe", "w"), // stdout is a pipe that the child will write to
        2 => array("file", "error-output.txt", "a")  // stderr is a file to write to
    );


    $pipes = array();

    $processHandle = proc_open($command, $descriptors, $pipes);

    if (is_resource($processHandle)) {     

        $processToSave = array(
            "process" => $processHandle,
            "pipes" => $pipes
        );

        file_put_contents("myfile.bin", serialize($processToSave) );        

    }

And in a second moment i need to retrieve this file handle from the file, i've used this code:

$processArray = unserialize(file_get_contents("myfile.bin"));  
$processHandle = $processArray["process"];
$pipes = $processArray["pipes"];

But when I print a var_dump of $processHandle and $pipes after retrieving from file, I'll get integers instead of resource or process, but why??

 var_dump($processHandle) ->  int(0)
 var_dump($pipes) - > array(2) { int(0), int(0) }

And at this point of course, if I try to close the pipes, i will get an error, resource expected, integer given.

How can I make this working? (NOTE: This is the solution I'm looking for)

But alternatively, I can get also the pid of process and then use this pid to stop or kill or do anything else with the process, but what about the pipes? How can I read/write or save error from/to the process?

Thank you

Upvotes: 1

Views: 709

Answers (1)

user2548436
user2548436

Reputation: 925

Found the solution to myself, it's not to possible to serialize resource and when the script has done, those resource handler were free.

Solution was to create a daemon listening on a port, wich on request launch and stop process. Because the process is always running, it can maintain a list of handler process and stop when requested.

Upvotes: 1

Related Questions