October 22, 2024
Chicago 12, Melborne City, USA
PHP

PHP proc_open stdout stream capturing file writes as well as text output


The platform is Linux. I have a C++ program that I wrote which displays text via cout and writes to a file via ofstream. I then run this program from PHP via proc_open and need to capture the cout text, but not the ofstream writes.

Is there any way to accomplish this, without outputting a token (e.g. "about to write to a file" and having php skip outputting after that)?

Relevant code snippets below:

PHP

function CCexecuteandprint($CCexecuteandprintCommand)
{
    $CCexecuteandprintDescriptor = array(0 => array("pipe","r"),1 => array("pipe","w"));
    $CCexecuteandprintPipes = array();
    $CCexecuteandprintProcess = proc_open($CCexecuteandprintCommand,$CCexecuteandprintDescriptor,$CCexecuteandprintPipes,getcwd(),null);
    $CCexecuteandprintOutput = "";

    if (is_resource($CCexecuteandprintProcess))
    {
        do
        {
            $CCexecuteandprintOutput = fgets($CCexecuteandprintPipes[1]);//wait for EoL
            CCimmediateoutput($CCexecuteandprintOutput.'<br />');
            $CCexecuteandprintStatus = proc_get_status($CCexecuteandprintProcess);
        }
        while($CCexecuteandprintStatus['running']);
    }
    else echo "Unable to start process\n";

    fclose($CCexecuteandprintPipes[0]);
    fclose($CCexecuteandprintPipes[1]);
    proc_close($CCexecuteandprintProcess);

C++

std::ofstream output("filename");
output << string1;
output.close();
output.clear();
output.open("nextfilename");
output << string2;
output.close();
output.clear();
output.open("lastfilename");
output << string3;
output.close();
output.clear();

The text capture is fine, but it’s also grabbing the file output. I expected it to capture only the text, mostly because I misinterpreted the proc_open manpage’s "stdout" as "text output".



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video