Jump to content

Determine if only one instance is running: Difference between revisions

→‎{{header|Go}}: add port based solution, simpler file based solution
m (→‎{{header|Sidef}}: modified the code to work with Sidef 2.30)
(→‎{{header|Go}}: add port based solution, simpler file based solution)
Line 374:
 
=={{header|Go}}==
===Port===
Solution using O_CREATE|O_EXCL, and with messages and a 10 second sleep to let you test it.
Recommended over file based solutions. It has the advantage that the port is always released
when the process ends.
<lang go>package main
 
import (
"fmt"
"net"
"time"
)
 
const lNet = "tcp"
const lAddr = ":12345"
 
func main() {
if _, err := net.Listen(lNet, lAddr); err != nil {
fmt.Println("an instance was already running")
return
}
fmt.Println("single instance started")
time.Sleep(10 * time.Second)
}</lang>
===File===
Solution using O_CREATE|O_EXCL. This solution has the problem that if anything terminates the
program early, the lock file remains.
<lang go>package main
 
import (
"fmt"
"os"
"time"
)
 
// The path to the lock file should be an absolute path starting from the root.
// (If you wish to prevent the same program running in different directories,
// that is.)
const lfn = "/tmp/rclock"
 
func main() {
lf, err := os.OpenFile(lfn, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
if err != nil {
fmt.Println("an instance is already running")
return
}
lf.Close()
fmt.Println("single instance started")
time.Sleep(10 * time.Second)
os.Remove(lfn)
}</lang>
Here's a fluffier version that stores the PID in the lock file to provide better messages.
It has the same problem of the lock file remaining if anything terminates the program early.
<lang go>package main
 
1,707

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.