0

I've created the following Go code to create run.stamp file for the period my app is running and delete it on exit.

    runStampFilename := path.Join(stateDirectory, "run.stamp")
    runStamp, err := os.OpenFile(runStampFilename, os.O_CREATE|os.O_EXCL, 0666)
    if err == os.ErrExist {
        fmt.Printf("File monitoring is already running, as signified by %s file", runStampFilename)
        os.Exit(1)
    } else if err != nil {
        fmt.Printf("Error: %s", err.Error())
        os.Exit(1)
    }
    defer os.Remove(runStampFilename)
    runStamp.Close()

But if the app is interrupted by Ctrl+C, the file is not deleted.

What is the best way to catch Ctrl+C and SIGTERM in Go?

And it must work in Windows, too. I would probably do it myself, without querying StackOverflow, but I don't have an idea how to do it in Windows.

I've changed my code to the following:

    runStampFilename := path.Join(stateDirectory, "run.stamp")
    defer os.Remove(runStampFilename)
    c := make(chan os.Signal, 1)
    signal.Notify(c, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
    go func() {
        for _ = range c {
            os.Remove(runStampFilename)
            os.Exit(0)
        }
    }()

    runStamp, err := os.OpenFile(runStampFilename, os.O_CREATE|os.O_EXCL, 0666)
    if err == os.ErrExist {
        fmt.Printf("File monitoring is already running, as signified by %s file", runStampFilename)
        os.Exit(1)
    } else if err != nil {
        fmt.Printf("Error: %s", err.Error())
        os.Exit(1)
    }
    runStamp.Close()

Is it now correct?

porton
  • 5,214
  • 11
  • 47
  • 95

0 Answers0