Created
March 28, 2013 17:54
-
-
Save gkristic/5265379 to your computer and use it in GitHub Desktop.
Proof of concept for deamons
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"os" | |
"log" | |
"time" | |
"syscall" | |
) | |
func main() { | |
tm := 15 | |
args := os.Args | |
dir, _ := os.Getwd() | |
attrs := os.ProcAttr{Dir: dir, Env: os.Environ(), Files: []*os.File{nil, nil, os.Stderr}} | |
if len(args) == 1 { | |
log.Printf("First instance; PID: %d\n", os.Getpid()) | |
args = []string{args[0], "second"} | |
tm = 10 | |
} else if args[1] == "second" { | |
log.Printf("Second instance; PID: %d\n", os.Getpid()) | |
args = []string{args[0], "third"} | |
tm = 5 | |
sysattr := syscall.SysProcAttr{Setsid: true} | |
attrs.Sys = &sysattr | |
} else if args[1] == "third" { | |
log.Printf("Third instance; PID: %d\n", os.Getpid()) | |
log.Printf("Process %d running for another %d seconds\n", os.Getpid(), tm) | |
time.Sleep(time.Duration(tm) * 1e9) | |
log.Printf("Process %d exiting\n", os.Getpid()) | |
os.Exit(0) | |
} | |
proc, err := os.StartProcess("fork2", args, &attrs) | |
if err != nil { | |
log.Printf("Unable to start process (my PID: %d)\n", os.Getpid()); | |
} | |
proc.Release() | |
log.Printf("Process %d running for another %d seconds\n", os.Getpid(), tm) | |
time.Sleep(time.Duration(tm) * 1e9) | |
log.Printf("Process %d exiting\n", os.Getpid()) | |
os.Exit(0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment