Jump to content

Run as a daemon or service: Difference between revisions

Added Go
(added Perl 6)
(Added Go)
Line 79:
$ pkill -x dumper
$ rm dump</pre>
 
=={{header|Go}}==
{{libheader|go-daemon}}
{{works with|Ubuntu 16.04}}
<lang go>package main
 
import (
"fmt"
"github.com/sevlyar/go-daemon"
"log"
"os"
"time"
)
 
func work() {
f, err := os.Create("daemon_output.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
ticker := time.NewTicker(time.Second)
go func() {
for t := range ticker.C {
fmt.Fprintln(f, t) // writes time to file every second
}
}()
time.Sleep(60 * time.Second) // stops after 60 seconds at most
ticker.Stop()
log.Print("ticker stopped")
}
 
func main() {
cntxt := &daemon.Context{
PidFileName: "pid",
PidFilePerm: 0644,
LogFileName: "log",
LogFilePerm: 0640,
WorkDir: "./",
Umask: 027,
Args: []string{"[Rosetta Code daemon example]"},
}
 
d, err := cntxt.Reborn()
if err != nil {
log.Fatal("Unable to run: ", err)
}
if d != nil {
return
}
defer cntxt.Release()
 
log.Print("- - - - - - - - - - - - - - -")
log.Print("daemon started")
 
work()
}</lang>
 
{{out}}
Although the daemon will only run for a maximum of 60 seconds, we kill it after a few seconds so the output is not too long.
<pre>
$ go build daemon.go
$ ./daemon
$ kill `cat pid`
$ cat log
2019/01/31 22:14:50 - - - - - - - - - - - - - - -
2019/01/31 22:14:50 daemon started
$ cat daemon_output.txt
2019-01-31 22:14:51.641498031 +0000 GMT m=+1.089305363
2019-01-31 22:14:52.641672923 +0000 GMT m=+2.089480618
2019-01-31 22:14:53.641724473 +0000 GMT m=+3.089531868
2019-01-31 22:14:54.641557151 +0000 GMT m=+4.089364696
2019-01-31 22:14:55.641543175 +0000 GMT m=+5.089350596
</pre>
 
=={{header|PARI/GP}}==
9,490

edits

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