summaryrefslogtreecommitdiffstats
path: root/src/runtime/internal/wasitest/testdata/nonblock.go
blob: 8cbf21b3a26d50cf62c90b129ee06d8a35934fab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"os"
	"sync"
	"syscall"
)

func main() {
	if len(os.Args) < 2 {
		panic("usage: nonblock <MODE> [PATH...]")
	}
	mode := os.Args[1]

	ready := make(chan struct{})

	var wg sync.WaitGroup
	for _, path := range os.Args[2:] {
		f, err := os.Open(path)
		if err != nil {
			panic(err)
		}
		switch mode {
		case "os.OpenFile":
		case "os.NewFile":
			fd := f.Fd()
			if err := syscall.SetNonblock(int(fd), true); err != nil {
				panic(err)
			}
			f = os.NewFile(fd, path)
		default:
			panic("invalid test mode")
		}

		spawnWait := make(chan struct{})

		wg.Add(1)
		go func(f *os.File) {
			defer f.Close()
			defer wg.Done()

			close(spawnWait)

			<-ready

			var buf [256]byte
			n, err := f.Read(buf[:])
			if err != nil {
				panic(err)
			}
			os.Stderr.Write(buf[:n])
		}(f)

		// Spawn one goroutine at a time.
		<-spawnWait
	}

	println("waiting")
	close(ready)
	wg.Wait()
}