--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
for example I have a program test.exe, I copy it to 2 dira/test.exeb/test.exethen a/test.exe and b/test.exe only one can run.I need both of it can run one instance.BTW, when program exit by accident , sometime the port will be locked, then it can't restart.
On Wed, 22 Jan 2014 00:39:08 -0800 (PST)
Hai Thanh Nguyen <phai...@gmail.com> wrote:
> Just write something to a file somewhere. Everytime your program is
> run, check that file. You don't need any fancy functionalities to do
> this.
[...] This moves us to the "PID file"
concept famous in classic Unix daemons -- a new instance of the daemon
is supposed to check if the PID file exists, and when it does whether
the process with this PID file exists, and if it does whether its
binary path name is that of the daemon. This is complicated and is
inherently racey.
So listening on a socket (not necessarily TCP -- Unix-domain socket
would do as well; on Linux it's possible to create an UD-socket which
does not physically exists on a file system) or connecting to d-bus and
requesting a well-known name would do as well in a non-racey fashion.
//oneinstance_windows.go
package oneinstance
import ( "fmt" "syscall" "unsafe")
var ( modkernel32 = syscall.NewLazyDLL("kernel32.dll") pCreateSemaphore = modkernel32.NewProc("CreateSemaphoreA") pGetLastError = modkernel32.NewProc("GetLastError"))
func GetLastError() uint32 { ret, _, _ := pGetLastError.Call() return uint32(ret)}
func GetInstance(ident string) error { semaphoreName := uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(`Global\` + ident))) //ret, _, _ := pCreateSemaphore.Call( pCreateSemaphore.Call( 0, uintptr(1), uintptr(1), semaphoreName, )
fmt.Println(GetLastError()) fmt.Println(syscall.GetLastError()) if GetLastError() != 0 { return syscall.GetLastError() } return nil}
package main
import ( "fmt" "os" "time"
)
func main() { err := oneinstance.GetInstance("foo") if err != nil { fmt.Println("Can't get semaphore:", err) os.Exit(1) }
fmt.Println("Got semaphore") time.Sleep(10 * time.Second)}
pCreateMutex.Call( 0, 1, semaphoreName, )