本文整理匯總了Golang中syscall.ForkExec函數的典型用法代碼示例。如果您正苦於以下問題:Golang ForkExec函數的具體用法?Golang ForkExec怎麽用?Golang ForkExec使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了ForkExec函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: ensureOwnerExists
// ensureOwnerExists makes sure that at least one owner exists in the database.
func (bot *Bot) ensureOwnerExists() {
result, err := bot.Db.Query(`SELECT EXISTS(SELECT 1 FROM users WHERE owner=1 LIMIT 1);`)
if err != nil {
bot.Log.Fatalf("Can't check if owner exists: %s", err)
}
defer result.Close()
if result.Next() {
var ownerExists bool
if err = result.Scan(&ownerExists); err != nil {
bot.Log.Fatalf("Can't check if owner exists: %s", err)
}
if !ownerExists {
bot.Log.Warningf("No owner found in the database. Must create one.")
stty, _ := exec.LookPath("stty")
sttyArgs := syscall.ProcAttr{
"",
[]string{},
[]uintptr{os.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd()},
nil,
}
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter owner's nick: ")
nick, _ := reader.ReadString('\n')
// Disable echo.
if stty != "" {
syscall.ForkExec(stty, []string{"stty", "-echo"}, &sttyArgs)
}
// Get password.
fmt.Print("Enter owner's password: ")
pass1, _ := reader.ReadString('\n')
fmt.Print("\nConfirm owner's password: ")
pass2, _ := reader.ReadString('\n')
if pass1 != pass2 {
bot.Log.Fatal("Passwords don't match.")
}
fmt.Print("\n")
// Enable echo.
if stty != "" {
syscall.ForkExec(stty, []string{"stty", "echo"}, &sttyArgs)
}
result.Close()
if bot.addUser(utils.CleanString(nick, false), utils.CleanString(pass1, false), true, true); err != nil {
bot.Log.Fatalf("%s", err)
}
}
}
}
示例2: echoOff
// echoOff turns off the terminal echo.
func echoOff(fd []uintptr) (int, error) {
pid, err := syscall.ForkExec(sttyArg0, sttyArgvEOff, &syscall.ProcAttr{Dir: "", Files: fd})
if err != nil {
return 0, fmt.Errorf("failed turning off console echo for password entry:\n\t%s", err)
}
return pid, nil
}
示例3: startPlugin
func (pluginReg *PluginReg) startPlugin(startFile string) (int, error) {
// Change the file permission
err := os.Chmod(startFile, 0777)
if err != nil {
log.DEBUG.Printf("Failed to change mode: %v", err)
return 0, err
}
dir := filepath.Dir(startFile)
startPath, _ := filepath.Abs(dir)
file := path.Base(startFile)
_, lookErr := exec.LookPath(startFile)
if lookErr != nil {
log.DEBUG.Printf("Lookerror")
return 0, lookErr
}
env := os.Environ()
attr := &syscall.ProcAttr{Dir: startPath, Env: env}
pid, execErr := syscall.ForkExec(file, nil, attr)
if execErr != nil {
log.DEBUG.Printf("Exeerror")
return 0, execErr
}
log.DEBUG.Printf("Started process: %d\n", pid)
return pid, nil
}
示例4: echoOn
// echoOn turns back on the terminal echo.
func echoOn(fd []uintptr) {
// Turn on the terminal echo.
pid, e := syscall.ForkExec(sttyArg0, sttyArgvEOn, &syscall.ProcAttr{Dir: "", Files: fd})
if e == nil {
syscall.Wait4(pid, nil, 0, nil)
}
}
示例5: execExternal
// execExternal executes an external command.
func (ev *Evaluator) execExternal(fm *form) <-chan *StateUpdate {
files := make([]uintptr, len(fm.ports))
for i, port := range fm.ports {
if port == nil || port.f == nil {
files[i] = FdNil
} else {
files[i] = port.f.Fd()
}
}
args := make([]string, len(fm.args)+1)
args[0] = fm.Path
for i, a := range fm.args {
// NOTE Maybe we should enfore string arguments instead of coercing all
// args into string
args[i+1] = a.String(ev)
}
sys := syscall.SysProcAttr{}
attr := syscall.ProcAttr{Env: ev.env.Export(), Files: files[:], Sys: &sys}
pid, err := syscall.ForkExec(fm.Path, args, &attr)
// Streams are closed after fork-exec of external is complete.
fm.closePorts(ev)
update := make(chan *StateUpdate)
if err != nil {
update <- &StateUpdate{Terminated: true, Msg: err.Error()}
close(update)
} else {
go waitStateUpdate(pid, update)
}
return update
}
示例6: maybeFork
// maybeFork will fork & detach if background is true. First it will rename the out and
// cache dirs so it's safe to run another plz in this repo, then fork & detach child
// processes to do the actual cleaning.
// The parent will then die quietly and the children will continue to actually remove the
// directories.
func maybeFork(outDir, cacheDir string, cleanCache bool) error {
rm, err := exec.LookPath("rm")
if err != nil {
return err
}
if !core.PathExists(outDir) || !core.PathExists(cacheDir) {
return nil
}
newOutDir, err := moveDir(outDir)
if err != nil {
return err
}
args := []string{rm, "-rf", newOutDir}
if cleanCache {
newCacheDir, err := moveDir(cacheDir)
if err != nil {
return err
}
args = append(args, newCacheDir)
}
// Note that we can't fork() directly and continue running Go code, but ForkExec() works okay.
_, err = syscall.ForkExec(rm, args, nil)
if err == nil {
// Success if we get here.
fmt.Println("Cleaning in background; you may continue to do pleasing things in this repo in the meantime.")
os.Exit(0)
}
return err
}
示例7: startNewProcess
// 啟動子進程執行新程序
func (this *Server) startNewProcess() error {
listenerFd, err := this.listener.(*Listener).GetFd()
if err != nil {
return fmt.Errorf("failed to get socket file descriptor: %v", err)
}
path := os.Args[0]
// 設置標識優雅重啟的環境變量
environList := []string{}
for _, value := range os.Environ() {
if value != GRACEFUL_ENVIRON_STRING {
environList = append(environList, value)
}
}
environList = append(environList, GRACEFUL_ENVIRON_STRING)
execSpec := &syscall.ProcAttr{
Env: environList,
Files: []uintptr{os.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd(), listenerFd},
}
fork, err := syscall.ForkExec(path, os.Args, execSpec)
if err != nil {
return fmt.Errorf("failed to forkexec: %v", err)
}
this.logf("start new process success, pid %d.", fork)
return nil
}
示例8: spawn
// spawn spawns the given filename in background using syscall
func spawn(name string) {
filepath := path.Join("/init/services", name)
stdinpath := path.Join("/logs/", name+".stdin")
stdoutpath := path.Join("/logs/", name+".stdout")
stderrpath := path.Join("/logs/", name+".stderr")
os.MkdirAll(path.Dir(stdinpath), 0777)
os.MkdirAll(path.Dir(stdoutpath), 0777)
os.MkdirAll(path.Dir(stderrpath), 0777)
fstdin, err := os.Create(stdinpath)
if err != nil {
log.Println("waat", err)
}
fstdout, err := os.Create(stdoutpath)
if err != nil {
log.Println("waat", err)
}
fstderr, err := os.Create(stderrpath)
if err != nil {
log.Println("waat", err)
}
// Open Files for stdout, stderr
procAttr := &syscall.ProcAttr{
Dir: "/",
Env: []string{"MYVAR=345"},
Files: []uintptr{fstdin.Fd(), fstdout.Fd(), fstderr.Fd()},
Sys: nil,
}
pid, err := syscall.ForkExec(filepath, nil, procAttr)
if err != nil {
log.WithFields(log.Fields{
"service": filepath,
"error": err,
}).Error("Could not start service.")
} else {
log.WithFields(log.Fields{
"service": filepath,
"pid": pid,
}).Info("Started service succesfully")
}
log.Info("Waiting for 3 seconds")
time.Sleep(3 * time.Second)
a, err1 := ioutil.ReadFile(stdoutpath)
b, err2 := ioutil.ReadFile(stderrpath)
if err1 != nil || err2 != nil {
log.Error("Could not read", err1, err2)
} else {
log.WithFields(log.Fields{
"service": name,
"stdout": string(a),
"stderr": string(b),
}).Info("Service ended.")
}
}
示例9: newDirCache
func newDirCache(config *core.Configuration) *dirCache {
cache := new(dirCache)
// Absolute paths are allowed. Relative paths are interpreted relative to the repo root.
if config.Cache.Dir[0] == '/' {
cache.Dir = config.Cache.Dir
} else {
cache.Dir = path.Join(core.RepoRoot, config.Cache.Dir)
}
// Make directory if it doesn't exist.
if err := os.MkdirAll(cache.Dir, core.DirPermissions); err != nil {
panic(fmt.Sprintf("Failed to create root cache directory %s: %s", cache.Dir, err))
}
// Fire off the cache cleaner process.
if config.Cache.DirCacheCleaner != "" && config.Cache.DirCacheCleaner != "none" {
go func() {
cleaner := core.ExpandHomePath(config.Cache.DirCacheCleaner)
log.Info("Running cache cleaner: %s --dir %s --high_water_mark %s --low_water_mark %s",
cleaner, cache.Dir, config.Cache.DirCacheHighWaterMark, config.Cache.DirCacheLowWaterMark)
if _, err := syscall.ForkExec(cleaner, []string{
cleaner,
"--dir", cache.Dir,
"--high_water_mark", config.Cache.DirCacheHighWaterMark,
"--low_water_mark", config.Cache.DirCacheLowWaterMark,
}, nil); err != nil {
log.Errorf("Failed to start cache cleaner: %s", err)
}
}()
}
return cache
}
示例10: Serve
func (s *Server) Serve() error {
log.Debug("this is ddbatman v4")
s.running = true
var sessionId int64 = 0
for s.running {
select {
case sessionChan <- sessionId:
//do nothing
default:
//warnning!
log.Warnf("TASK_CHANNEL is full!")
}
conn, err := s.Accept()
if err != nil {
log.Warning("accept error %s", err.Error())
continue
}
//allocate a sessionId for a session
go s.onConn(conn)
sessionId += 1
}
if s.restart == true {
log.Debug("Begin to restart graceful")
listenerFile, err := s.listener.(*net.TCPListener).File()
if err != nil {
log.Fatal("Fail to get socket file descriptor:", err)
}
listenerFd := listenerFile.Fd()
os.Setenv("_GRACEFUL_RESTART", "true")
execSpec := &syscall.ProcAttr{
Env: os.Environ(),
Files: []uintptr{os.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd(), listenerFd},
}
fork, err := syscall.ForkExec(os.Args[0], os.Args, execSpec)
if err != nil {
return fmt.Errorf("failed to forkexec: %v", err)
}
log.Infof("start new process success, pid %d.", fork)
}
timeout := time.NewTimer(time.Minute)
wait := make(chan struct{})
go func() {
s.wg.Wait()
wait <- struct{}{}
}()
select {
case <-timeout.C:
log.Error("server : Waittimeout error when close the service")
return nil
case <-wait:
log.Info("server : all goroutine has been done")
return nil
}
return nil
}
示例11: echoOff
func echoOff(pa syscall.ProcAttr) int {
pid, err := syscall.ForkExec(sttyCmd, sttyArgvEchoOff, &pa)
if err != nil {
fmt.Printf("Error setting echo off: %s\n", err)
}
return pid
}
示例12: echoOn
func echoOn(pa syscall.ProcAttr) {
pid, err := syscall.ForkExec(sttyCmd, sttyArgvEchoOn, &pa)
if err == nil {
syscall.Wait4(pid, &waitStatus, 0, nil)
} else {
fmt.Printf("Error setting echo on: %s\n", err)
}
}
示例13: echoOff
func echoOff(fd []uintptr) (int, error) {
pid, err := syscall.ForkExec(sttyArg0, sttyArgvEOff, &syscall.ProcAttr{Dir: exec_cwdir, Files: fd})
if err != nil {
return 0, fmt.Errorf("failed turning off console echo for password entry:\n{{.ErrorDescription}}", map[string]interface{}{"ErrorDescription": err})
}
return pid, nil
}
示例14: forker
// setup and fork/exec myself. Make sure to keep open important FD's that won't get re-created by the child
// specifically, std* and your listen socket
func forker(srv *falcore.Server) (pid int, err int) {
fmt.Printf("Forking now with socket: %v\n", srv.SocketFd())
mypath := os.Args[0]
args := []string{mypath, "-socket", fmt.Sprintf("%v", srv.SocketFd())}
attr := new(syscall.ProcAttr)
attr.Files = append([]int(nil), 0, 1, 2, srv.SocketFd())
pid, err = syscall.ForkExec(mypath, args, attr)
return
}
示例15: echoOff
func echoOff(fd []uintptr) (int, error) {
pid, err := syscall.ForkExec(sttyArg0, sttyArgvEOff, &syscall.ProcAttr{Dir: exec_cwdir, Files: fd})
if err != nil {
//Removed error and replaced with nil
return 0, nil
}
return pid, nil
}