Skip to content

Instantly share code, notes, and snippets.

@ericchiang
Last active September 19, 2023 20:26
Show Gist options
  • Save ericchiang/ce0fdcac5659d0a80b38 to your computer and use it in GitHub Desktop.
Save ericchiang/ce0fdcac5659d0a80b38 to your computer and use it in GitHub Desktop.
Golang Flock
package main
// #include <sys/file.h>
import "C"
import (
"fmt"
"os"
"os/exec"
)
func main() {
fi, err := os.Create("lock")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer fi.Close()
fd := fi.Fd()
returnCode := C.flock(C.int(fd), C.LOCK_EX)
if returnCode < 0 {
fmt.Println("Flock lock returned bad status: %d", returnCode)
os.Exit(2)
}
if len(os.Args) > 1 {
cmd := exec.Command(os.Args[1], os.Args[2:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
if err := cmd.Run(); err != nil {
fmt.Println(err)
}
}
returnCode = C.flock(C.int(fd), C.LOCK_UN)
if returnCode < 0 {
fmt.Println("Flock unlock returned bad status: %d", returnCode)
os.Exit(2)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment