What's the best way to implement a semaphore in Go -
i have test program want run multiple copies of program command-line, , need know first instance of program start. in dart, following suggested me :
rawserversocket.bind("127.0.0.1", 8087)
if fails, know program has "locked" port. solves problem sufficiently me. lock released when program terminates or when socket explicitly closed.
how can achieve similar result in go?
you don't platform using. if want cross platform solution of opening local socket easy. here how in go.
package main import ( "log" "net" "time" ) func main() { ln, err := net.listen("tcp", "127.0.0.1:9876") if err != nil { log.fatal("failed lock: ", err) } defer ln.close() log.print("started") time.sleep(time.second * 10) log.print("ending") }
a cross platform way of doing without using socket quite hard unfortunately , involve 2 sets of code 1 unix systems , 1 windows.
note virus checkers don't programs opening listening sockets on windows...
Comments
Post a Comment