process icon indicating copy to clipboard operation
process copied to clipboard

Process getting stuck because of a full STDOUT/STDERR pipe

Open nanawel opened this issue 2 years ago • 2 comments

This is not a bug, only a little help that might be useful for some people passing through here.

It might be worth noting a scenario I've just encountered: I'm running a ffmpeg command with amphp/process and I was only interested in what was produced by STDOUT (wav audio).

So basically it was as simple as:

$command = sprintf('ffmpeg -i %s -f wav -ac 1 -c:a pcm_s16le -ar 16000 pipe:1', escapeshellarg($filePath));
$process = Process::start($command);
while (($chunk = $process->getStdout()->read()) !== null) {
    // ... do stuff
}
$process->join();

But I noticed that for some reason, the process got eventually stuck on the read() and could go no further. After digging for a while, and remembering a similar situation using the native proc_open() with $pipes, I understood that it was not because I didn't care about STDERR in my case, that the corresponding pipe was not filling up anyway! Until it was completely full and the process got stuck, waiting for the pipe to be read/emptied.

In this precise case, the optimal solution is not to fill STDERR in the first place, using the options -hide_banner -loglevel quiet for ffmpeg, but if you cannot control the command's output, I suppose you can use this:

async(
    ByteStream\pipe(...),
    $process->getStderr(),
    new WritableResourceStream(\fopen('/dev/null', 'wb'))
)->ignore();

Feel free to correct me. I did not test this solution myself but I thought it was important to mention.

nanawel avatar Feb 11 '24 15:02 nanawel

I found this comment useful as it pointed me a direction to go when I encountered hanging (everlasting) subprocesses. Please do not close it. Thank you @nanawel for sharing your knowledge!

roomcays avatar Jan 10 '25 13:01 roomcays

@roomcays Could you send a PR to the README with documentation so we can close this?

kelunik avatar Jan 10 '25 14:01 kelunik