Last active
May 18, 2018 05:38
-
-
Save hxy9243/6926abe93e4ca34c57fcbfade6309054 to your computer and use it in GitHub Desktop.
Useful go snippets
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" | |
"syscall" | |
"os/exec" | |
"fmt" | |
) | |
// Start daemon function | |
// Works under linux, not tested with other platforms | |
func StartDaemon(name string, arg ...string) (int, error) { | |
ret, ret2, syserr := syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0) | |
if syserr != 0 || ret < 0 || ret2 < 0 { | |
return -1, fmt.Errorf("Error forking child process") | |
} | |
// parent process | |
if ret > 0 { | |
return int(ret), nil | |
} else { | |
// clear umask | |
_ = syscall.Umask(0) | |
syscall.Setsid() | |
err := exec.Command(name, arg...).Run() | |
if err != nil { | |
os.Exit(1) | |
} else { | |
os.Exit(0) | |
} | |
} | |
return 0, nil | |
} | |
func main() { | |
pid, err := StartDaemon("sleep", "30") | |
if err != nil { | |
fmt.Fprintln(os.Stderr, "Spawned subprocess: ", pid) | |
os.Exit(1) | |
} else { | |
fmt.Println("Spawned subprocess: ", pid) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment