Created
July 8, 2020 13:25
-
-
Save mittachaitu/9a5b8f4f06d05a8bdfb19290194d2e4d to your computer and use it in GitHub Desktop.
It opens the blockfile and doesn't close the fd. Leaving the responsibility to go GC to close the fd
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"runtime" | |
"sync" | |
"time" | |
) | |
var wg *sync.WaitGroup | |
func test() { | |
defer wg.Done() | |
f, err := os.OpenFile("/dev/sdb1", os.O_EXCL, 0444) | |
if err != nil { | |
fmt.Printf("Failed to open /dev/sdb1 file %v\n", err) | |
return | |
} | |
// add finalizer which just prints once it was garbage collected | |
runtime.SetFinalizer(f, func(f *os.File) { fmt.Printf("Garbage collected the value %+v\n", f) }) | |
fmt.Printf("Opend /dev/sdb1 file ===> File %+v, fd: %+v\n", f, f.Fd()) | |
time.Sleep(10 * time.Second) | |
} | |
func main() { | |
wg = &sync.WaitGroup{} | |
wg.Add(1) | |
// Nothing to worry about it launched one go routine and used to waitGroup | |
// to synchronize it | |
go test() | |
wg.Wait() | |
// run garbage collection to close the fd | |
runtime.GC() | |
fmt.Println("Successfully ran the garbage collection") | |
// sleep to switch to finalizer goroutine | |
time.Sleep(1 * time.Hour) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment