Skip to content

net: Listener.Close() does not fully stop the server when Accept()'ing at the same time #22502

Closed
@akyoto

Description

@akyoto

What version of Go are you using (go version)?

go version go1.9.2 linux/amd64

Does this issue reproduce with the latest release?

Yes.

What operating system and processor architecture are you using (go env)?

GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/eduard/workspace"
GORACE=""
GOROOT="/usr/local/go"
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build249817023=/tmp/go-build -gno-record-gcc-switches"
CXX="g++"
CGO_ENABLED="1"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"

What did you do?

Run this:

package main

import (
	"fmt"
	"net"
)

func main() {
	i := 0

	for {
		listener, err := net.Listen("tcp", ":3000")

		if err != nil {
			fmt.Printf("failure @ iteration %d | %s\n", i, err)
			i++
			continue
		}

		go accept(listener)
		// time.Sleep(100 * time.Millisecond)
		err = listener.Close()

		if err != nil {
			fmt.Printf("close failure @ iteration %d | %s\n", i, err)
		}

		i++
	}
}

func accept(listener net.Listener) {
	for {
		_, err := listener.Accept()

		if err != nil {
			break
		}
	}
}

What did you expect to see?

I expected the listener.Close call to fully stop the server in every iteration. No failures.

What did you see instead?

When you listener.Accept in another goroutine, the Close call doesn't always complete in time and the server stays alive. This is especially annoying for writing tests where each test opens a new server and closes it via defer. Some tests can't start the server because the server from the previous test hasn't been killed yet.

References:
https://github.com/blitzprog/go-tests/blob/master/net-listener-close/net-listener-close.go
https://github.com/aerogo/nano

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions