github.com/keybase/client/go@v0.0.0-20241007131713-f10651d043c8/libcmdline/fork_nix.go (about)

     1  // Copyright 2018 Keybase, Inc. All rights reserved. Use of
     2  // this source code is governed by the included BSD license.
     3  
     4  //go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
     5  // +build darwin dragonfly freebsd linux netbsd openbsd solaris
     6  
     7  package libcmdline
     8  
     9  import (
    10  	"os"
    11  	"syscall"
    12  
    13  	"github.com/keybase/client/go/logger"
    14  )
    15  
    16  // SpawnDetachedProcess spawns a background process and detech from the calling
    17  // process.
    18  func SpawnDetachedProcess(
    19  	cmd string, args []string, _ logger.Logger) (pid int, err error) {
    20  	var files []uintptr
    21  	var devnull *os.File
    22  
    23  	defer func() {
    24  		if err != nil && devnull != nil {
    25  			devnull.Close()
    26  		}
    27  	}()
    28  
    29  	if devnull, err = os.OpenFile("/dev/null", os.O_RDONLY, 0); err != nil {
    30  		return
    31  	}
    32  	nullfd := devnull.Fd()
    33  	files = append(files, nullfd, nullfd, nullfd)
    34  
    35  	attr := syscall.ProcAttr{
    36  		Env:   os.Environ(),
    37  		Sys:   &syscall.SysProcAttr{Setsid: true},
    38  		Files: files,
    39  	}
    40  
    41  	pid, err = syscall.ForkExec(cmd, args, &attr)
    42  	return pid, err
    43  }