Service not starting after restart or user logins after shutdown.
mai1x9 opened this issue · comments
Code main.go
Simple code whose task is to write to file every 1 second. (code inside run function). I am writing to C drive, test.txt. File location
C:\\test.txt
Full code:
package main
import (
"log"
"os"
"strconv"
"time"
"github.com/kardianos/service"
)
var logger service.Logger
type program struct{}
func (p *program) Start(s service.Service) error {
// Start should not block. Do the actual work async.
go p.run()
return nil
}
func (p *program) run() {
fname := "C:\\test.txt"
f, err := os.OpenFile(fname, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
panic(err)
}
defer f.Close()
text := "hellowrold ......... "
counter := 0
strint := ""
for true {
strint = strconv.Itoa(counter)
if _, err = f.WriteString(text + strint + "\n"); err != nil {
panic(err)
}
counter++
time.Sleep(1 * time.Second)
}
}
func (p *program) Stop(s service.Service) error {
// Stop should not block. Return with a few seconds.
return nil
}
func main() {
svcConfig := &service.Config{
Name: "GoServiceExampleSimple",
DisplayName: "Go Service Example",
Description: "This is an example Go service.",
}
prg := &program{}
s, err := service.New(prg, svcConfig)
if err != nil {
log.Fatal(err)
}
logger, err = s.Logger(nil)
if err != nil {
log.Fatal(err)
}
err = s.Run()
if err != nil {
logger.Error(err)
}
}
I have registered the final executable using sc.exe with admin rights.
Steps followed:
- go build main
- Moved the main.exe to ProgramData/sc. So main.exe fullpath is
C:\\ProgramData\sc\main.exe
. - ran the command
sc.exe create GOServiceTest binpath= "C:\Program Files\sc\main.exe" start= auto
- I have set type=auto to automatically start after reboot or user logins.
- sc.exe start GOServiceTest works perfectly fine and writes to the file.
- I have now stopped the service using sc.exe stop GOServiceTest
However when I restart, shutdown system and login again, I see GoServiceTest is stopped and did not run and write anything to file.
Why did the exe did not start after reboot?
However, when I keep running GOServiceTest, and restart, or reboot then I can see the service is running, but to my great surpise the PID of the process is same and the service instead of starting, it continued from where it left. (I have kept counter which increases every second by 1. After restart, the counter value did not reset to zero and continued from where it was last stopped.)