# Immediately terminating a pipe

**URL:** <https://www.ruby-forum.com/t/immediately-terminating-a-pipe/108800>\
**Category:** Ruby\
**Created:** [July 7, 2007, 7:19am UTC](https://www.ruby-forum.com/t/immediately-terminating-a-pipe/108800 "2007-07-07T07:19:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Matthieu\_R](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/3bc359/32.png) [@Matthieu\_R](https://www.ruby-forum.com/u/Matthieu_R)\
**Post date:** [July 7, 2007, 7:19am UTC](https://www.ruby-forum.com/t/immediately-terminating-a-pipe/108800/1 "2007-07-07T07:19:11Z")

</div>

Hi,

I’m opening a pipe and forking a command using popen3 to send it some  
data.  
However the data “accumulates” so even if I close the stream, the  
command  
continues running for a little while. In my case I’d like to find a way  
to  
stop it immediately. This explanation doesn’t sound very clear so let me  
elaborate with an example.

Say that I want to stream some music to mpg123 to get it played. I can  
do  
something like:

require ‘open3’  
mpg\_in, mpg\_out, mpg\_err = Open3.popen3(“mpg123 -q -”)  
f = File.new(“Placebo - Pure Morning.mp3”)  
200.times { mpg\_in.write f.read(1024) }  
mpg\_in.close

You’ll notice that the music continues playing after exiting the loop  
for a  
little while even though the input stream has been closed. I’d like it  
to  
stop immediately. I guess there must be a buffer or something.

The only solution I’ve found so far is to kill the forked process (in  
that  
case mpg123) when I really want it to stop. And there’s one more problem  
here: popen3 doesn’t give you the forked process id . So I have to hack  
Open3 to give me the forked process id.

Anybody has a better idea? Any more elegant alternative than killing?

Thanks!  
Matthieu

---

<div class="post-metadata">

**Author:** ![Matthieu\_R](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/3bc359/32.png) [@Matthieu\_R](https://www.ruby-forum.com/u/Matthieu_R)\
**Post date:** [July 7, 2007, 7:38am UTC](https://www.ruby-forum.com/t/immediately-terminating-a-pipe/108800/2 "2007-07-07T07:38:12Z")

</div>

On Jul 6, 2007, at 11:18 PM, Matthieu R. wrote:

> And there’s one more problem  
> here: popen3 doesn’t give you the forked process id . So I have to  
> hack  
> Open3 to give me the forked process id.

[http://codeforpeople.com/lib/ruby/open4/open4-0.9.3/README](http://codeforpeople.com/lib/ruby/open4/open4-0.9.3/README)

gem install open4

-a
