LoginSignup
8

More than 5 years have passed since last update.

Go製のサーバーで起動時にPIDファイルを作る

Posted at

Goで書かれているサーバーのPIDファイルが欲しいとなったとします。start-stop-daemonとか使っているならPIDファイルを作ってくれる機能があるのでそれに乗っかるのがいいと思いますが、そういった機能がないものを使ってデーモン化している場合は自前でPIDファイルを作る必要があります。

というわけで以下のような感じにしてみました。

package main

import (
    "fmt"
    "os"
    "syscall"
)

func init() {
    pidFilePath := "tmp.pid"
    if ferr := os.Remove(pidFilePath); ferr != nil {
        if !os.IsNotExist(ferr) {
            panic(ferr.Error())
        }
    }
    pidf, perr := os.OpenFile(pidFilePath, os.O_EXCL|os.O_CREATE|os.O_WRONLY, 0666)

    if perr != nil {
        panic(perr.Error())
    }
    if _, err := fmt.Fprint(pidf, syscall.Getpid()); err != nil {
        panic(err.Error())
    }
    pidf.Close()
}

func main() {
}

PIDファイルは起動時に一旦削除してファイルを開きます。今回はファイルを開く時にファイルが存在しないことを保証したかったのでos.O_EXCL|os.O_CREATEを指定しています。PIDはとりあえずsyscall.Getpid()で取れるのでこれを書き込んでファイルをCloseすれば起動時にPIDファイルをさくっと書き込んでファイルディスクリプタを手放します。

とりあえず普通に動くので参考までに。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
8