set variables before daemon
doomedramen opened this issue · comments
I would like to use this library but I am not sure if it is possible to do the following.
When the code is run it will ask for a username and password.
The daemon then starts.
The child process should use the username and password provided in the parent process to check authentication of a url (on a loop).
currently using the library I just get a infinate loop of asking for a username and password (I understand why) but I dont not see how to pass variables from parent to child.
@wookoouk I had to do something similar and was running into an issue with flags not being able to be read when the child process starts. I was passing in strings directly instead of prompting but I think you could follow my solution.
Things I had to do to get it working:
- check if it is currently inside a child process or not
- set variables as environment variables in order to pass it to the child
package main
import (
"flag"
"fmt"
"log"
"os"
"time"
"github.com/sevlyar/go-daemon"
)
func main() {
var user string
var pw string
var envVars []string
// parent process
if !daemon.WasReborn() {
flag.StringVar(&user, "user", "", "username")
flag.StringVar(&pw, "pw", "", "password")
flag.Parse()
if user == "" {
fmt.Println("user flag is empty")
os.Exit(1)
} else if pw == "" {
fmt.Println("pw flag is empty")
os.Exit(1)
}
checkAuth(user, pw)
// get list of current env to pass to child process
var currEnv []string
for _, e := range os.Environ() {
currEnv = append(currEnv, e)
}
// add token value for child process to read
envVars = append(currEnv, "USER="+user)
envVars = append(envVars, "PASS="+pw)
} else { // child process
user = os.Getenv("USER")
pw = os.Getenv("PASS")
}
cntxt := &daemon.Context{
PidFileName: "log",
PidFilePerm: 0644,
LogFileName: "pid",
LogFilePerm: 0640,
WorkDir: "./",
Umask: 027,
Env: envVars,
Args: []string{"[go-daemon sample]"},
}
d, err := cntxt.Reborn()
if err != nil {
log.Fatalln(err)
}
if d != nil {
return
}
defer cntxt.Release()
log.Println("- - - - - - - - - - - - - - -")
log.Println("daemon started")
worker(user, pw)
}
func worker(user string, pw string) {
for {
time.Sleep(20 * time.Minute)
checkAuth(user, pw)
}
}
func checkAuth(user string, pw string) {
//do stuff
}
Thanks @dpoll, it works!