Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix deadlock when closing pipe #324

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions pipe.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"net"
"os"
"runtime"
"sync"
"time"
"unsafe"

Expand Down Expand Up @@ -316,8 +317,9 @@ type win32PipeListener struct {
path string
config PipeConfig
acceptCh chan (chan acceptResponse)
closeCh chan int
doneCh chan int
closeOnce sync.Once
closeCh chan struct{}
doneCh chan struct{}
}

func makeServerPipeHandle(path string, sd []byte, c *PipeConfig, first bool) (windows.Handle, error) {
Expand Down Expand Up @@ -530,8 +532,8 @@ func ListenPipe(path string, c *PipeConfig) (net.Listener, error) {
path: path,
config: *c,
acceptCh: make(chan (chan acceptResponse)),
closeCh: make(chan int),
doneCh: make(chan int),
closeCh: make(chan struct{}),
doneCh: make(chan struct{}),
}
go l.listenerRoutine()
return l, nil
Expand Down Expand Up @@ -573,11 +575,10 @@ func (l *win32PipeListener) Accept() (net.Conn, error) {
}

func (l *win32PipeListener) Close() error {
select {
case l.closeCh <- 1:
<-l.doneCh
case <-l.doneCh:
}
l.closeOnce.Do(func() {
close(l.closeCh)
})
<-l.doneCh
return nil
}

Expand Down
44 changes: 44 additions & 0 deletions pipe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -644,5 +644,49 @@ func TestListenConnectRace(t *testing.T) {
s.Close()
}
wg.Wait()

t.Logf("iteration %d", i)
}
}

func TestCloseRace(t *testing.T) {
for i := 0; i < 1000 && !t.Failed(); i++ {
l, err := ListenPipe(testPipeName, &PipeConfig{MessageMode: true})
if err != nil {
t.Fatal(err)
}
go func() {
for {
c, err := l.Accept()
if err != nil {
return
}
b, err := io.ReadAll(c)
if err != nil {
t.Error(err)
return
}
_, _ = c.Write(b)
_ = c.Close()
}
}()

c, err := DialPipe(testPipeName, nil)
if err != nil {
t.Fatal(err)
}
if _, err = c.Write([]byte("hello")); err != nil {
t.Fatal(err)
}
if err := c.(CloseWriter).CloseWrite(); err != nil {
t.Fatal(err)
}
if _, err := io.ReadAll(c); err != nil {
t.Fatal(err)
}
_ = c.Close()
_ = l.Close()

t.Logf("iteration %d", i)
}
}
Loading