示例#1
0
func daemon(nochdir, noclose int) int {
	var ret uintptr
	var err syscall.Errno

	ret, _, err = syscall.Syscall(syscall.SYS_FORK, 0, 0, 0)
	if err != 0 {
		return -1
	}
	switch ret {
	case 0:
		break
	default:
		os.Exit(0)
	}
	pid, _ := syscall.Setsid()
	if pid == -1 {
		return -1
	}
	if nochdir == 0 {
		os.Chdir("/")
	}
	if noclose == 0 {
		f, e := os.Open("/dev/null")
		if e == nil {
			fd := int(f.Fd())
			syscall.Dup2(fd, int(os.Stdin.Fd()))
			syscall.Dup2(fd, int(os.Stdout.Fd()))
			syscall.Dup2(fd, int(os.Stderr.Fd()))
		}
	}
	return 0
}
示例#2
0
func CaptureStream(file *os.File) (*os.File, func(), error) {
	pipeR, pipeW, err := os.Pipe()
	if err != nil {
		return nil, nil, err
	}

	bkupFD, err := syscall.Dup(int(file.Fd()))
	if err != nil {
		pipeW.Close()
		pipeR.Close()
		return nil, nil, err
	}

	err = syscall.Dup2(int(pipeW.Fd()), int(file.Fd()))
	if err != nil {
		syscall.Close(bkupFD)
		pipeW.Close()
		pipeR.Close()
	}

	cleanFunc := func() {
		syscall.Dup2(bkupFD, int(file.Fd()))
		syscall.Close(bkupFD)
		pipeW.Close()
		pipeR.Close()
	}

	return pipeR, cleanFunc, nil
}
示例#3
0
func (this torUtil) SetDaemonMode(nochdir, noclose int) int {
	if syscall.Getppid() == 1 {
		return 0
	}
	ret, ret2, err := syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0)
	if err != 0 {
		return -1
	}
	if ret2 < 0 {
		os.Exit(-1)
	}
	if ret > 0 {
		os.Exit(0)
	}
	syscall.Umask(0)
	s_ret, s_errno := syscall.Setsid()
	if s_ret < 0 {
		return -1
	}
	if nochdir == 0 {
		os.Chdir("/")
	}
	if noclose == 0 {
		f, e := os.OpenFile("/dev/null", os.O_RDWR, 0)
		if e == nil {
			fd := f.Fd()
			syscall.Dup2(int(fd), int(os.Stdin.Fd()))
			syscall.Dup2(int(fd), int(os.Stdout.Fd()))
			syscall.Dup2(int(fd), int(os.Stderr.Fd()))
		}
	}
	return 0
}
示例#4
0
文件: daemon.go 项目: dogeerf/tool
func daemon(nochdir, noclose int) int {
	var ret, ret2 uintptr
	var err syscall.Errno

	darwin := runtime.GOOS == "darwin"

	// already a daemon
	if syscall.Getppid() == 1 {
		return 0
	}

	// fork off the parent process
	ret, ret2, err = syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0)
	if err != 0 {
		return -1
	}

	// failure
	if ret2 < 0 {
		os.Exit(-1)
	}

	// handle exception for darwin
	if darwin && ret2 == 1 {
		ret = 0
	}

	// if we got a good PID, then we call exit the parent process.
	if ret > 0 {
		os.Exit(0)
	}

	/* Change the file mode mask */
	_ = syscall.Umask(0)

	// create a new SID for the child process
	s_ret, s_errno := syscall.Setsid()
	if s_errno != nil {
		log.Printf("Error: syscall.Setsid errno: %d", s_errno)
	}
	if s_ret < 0 {
		return -1
	}

	if nochdir == 0 {
		os.Chdir("/")
	}

	if noclose == 0 {
		f, e := os.OpenFile("/dev/null", os.O_RDWR, 0)
		if e == nil {
			fd := f.Fd()
			syscall.Dup2(int(fd), int(os.Stdin.Fd()))
			syscall.Dup2(int(fd), int(os.Stdout.Fd()))
			syscall.Dup2(int(fd), int(os.Stderr.Fd()))
		}
	}

	return 0
}
func (interceptor *outputInterceptor) StartInterceptingOutput() error {
	if interceptor.intercepting {
		return errors.New("Already intercepting output!")
	}
	interceptor.intercepting = true

	var err error

	interceptor.redirectFile, err = ioutil.TempFile("", "ginkgo")
	if err != nil {
		return err
	}

	interceptor.stdoutPlaceholder, err = ioutil.TempFile("", "ginkgo")
	if err != nil {
		return err
	}

	interceptor.stderrPlaceholder, err = ioutil.TempFile("", "ginkgo")
	if err != nil {
		return err
	}

	syscall.Dup2(1, int(interceptor.stdoutPlaceholder.Fd()))
	syscall.Dup2(2, int(interceptor.stderrPlaceholder.Fd()))

	syscall.Dup2(int(interceptor.redirectFile.Fd()), 1)
	syscall.Dup2(int(interceptor.redirectFile.Fd()), 2)

	return nil
}
示例#6
0
func initLogging(logLevelStr string, logPath string) {
	logLevel, err := logging.LogLevel(logLevelStr)
	if err != nil {
		log.Fatal("Invalid log level specified")
	}

	var formatStdout = logging.MustStringFormatter(
		"%{color}%{time:15:04:05.000} %{shortfunc} ▶ %{level:.4s} %{color:reset} %{message}",
	)
	stdout := logging.NewLogBackend(os.Stdout, "", 0)
	formatter := logging.NewBackendFormatter(stdout, formatStdout)
	stdoutLeveled := logging.AddModuleLevel(formatter)
	stdoutLeveled.SetLevel(logLevel, "")
	syslogBackend, err := logging.NewSyslogBackendPriority("cluegetter", syslog.LOG_MAIL)
	if err != nil {
		Log.Fatal(err)
	}

	if logPath != "" {
		logFile, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND, 0644)
		if err != nil {
			Log.Fatal(err)
		}
		syscall.Dup2(int(logFile.Fd()), 1)
		syscall.Dup2(int(logFile.Fd()), 2)
	}

	logging.SetBackend(syslogBackend, stdoutLeveled)
}
示例#7
0
// Initializes logrus.  Returns a pointer to `os.File` that should be `Close`d
// via `defer` in the main func.
func InitLogging(debug bool, logFile string) *os.File {
	var logFp *os.File

	if debug {
		log.SetLevel(log.DebugLevel)
	}

	if logFile != "" {
		logFp, err := os.OpenFile(logFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
		CheckError(fmt.Sprintf("error opening %s", logFile), err)

		// ensure panic output goes to log file
		syscall.Dup2(int(logFp.Fd()), 1)
		syscall.Dup2(int(logFp.Fd()), 2)

		// log as JSON
		log.SetFormatter(&log.JSONFormatter{})

		// send output to file
		log.SetOutput(logFp)
	}

	workers.Logger = log.WithField("name", "worker")

	return logFp
}
示例#8
0
func Daemonize() (e error) {
	// var ret, err uintptr
	ret, _, err := syscall.Syscall(syscall.SYS_FORK, 0, 0, 0)
	if err != 0 {
		return fmt.Errorf("fork error: %d", err)
	}
	if ret != 0 {
		// Parent
		os.Exit(0)
	}

	// We are now child

	if err, _ := syscall.Setsid(); err < 0 {
		return fmt.Errorf("setsid error: %d", err)
	}

	os.Chdir("/")
	f, e := os.OpenFile(os.DevNull, os.O_RDWR, 0)
	if e != nil {
		return
	}
	fd := int(f.Fd())
	syscall.Dup2(fd, int(os.Stdin.Fd()))
	syscall.Dup2(fd, int(os.Stdout.Fd()))
	syscall.Dup2(fd, int(os.Stderr.Fd()))

	return nil
}
示例#9
0
func main() {
	// Prepare the HTTP server
	server := &http.Server{
		Addr: "127.0.0.1:8081",
	}

	metricsPort := "8082"
	flag.StringVar(&metricsPort, "mport", metricsPort, "metrics service port")
	flag.StringVar(&server.Addr, "addr", server.Addr, "http service address (TCP address or absolute path for UNIX socket)")
	origin := flag.String("origin", "", "websocket server checks Origin headers against this scheme://host[:port]")
	logpath := flag.String("log", "", "Log file (absolute path)")

	flag.Parse()

	if strings.HasPrefix(*logpath, "/") {
		logf, err := os.OpenFile(*logpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			log.Fatalf("error opening log file: %v", err)
		}
		defer func() {
			log.Printf("********** pid %d stopping **********", os.Getpid())
			logf.Close()
		}()
		if err = syscall.Dup2(int(logf.Fd()), syscall.Stdout); err != nil {
			log.Fatalf("error redirecting stdout to file: %v", err)
		}
		if err = syscall.Dup2(int(logf.Fd()), syscall.Stderr); err != nil {
			log.Fatalf("error redirecting stderr to file: %v", err)
		}
		log.SetFlags(log.Ldate | log.Lmicroseconds | log.LUTC)
		log.Printf("********** pid %d starting **********", os.Getpid())
	}

	// Initialize metrics registry with expected stats
	go startMetrics(metricsPort)
	incr("websockets", 0)    // number of connected websockets
	incr("channels", 0)      // number of subscribed channels
	mark("postmsgs", 0)      // rate of POST messages
	mark("websocketmsgs", 0) // rate of WS messages
	mark("drops", 0)         // rate of messages sent to nobody
	mark("sends", 0)         // rate of messages sent to somebody

	// Start the server
	server.Handler = newHandler(*origin)
	http.Handle("/", server.Handler)
	if strings.HasPrefix(server.Addr, "/") {
		ln, err := net.Listen("unix", server.Addr)
		if err != nil {
			panic(err)
		}
		closeListenerOnSignals(ln)
		server.Serve(ln)
	} else {
		server.ListenAndServe()
	}
}
示例#10
0
文件: daemon.go 项目: slene/gocase
func _not_work_Fork(closeno bool) (pid int, err error) {
	// don't run this
	// not work with go threads
	// see: http://code.google.com/p/go/issues/detail?id=227

	darwin := runtime.GOOS == "darwin"

	// already a daemon
	if syscall.Getppid() == 1 {
		return 0, nil
	}

	// fork off the parent process
	ret, ret2, errno := syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0)

	if errno != 0 {
		return -1, fmt.Errorf("Fork failure: %s", errno)
	}

	// failure
	if ret2 < 0 {
		return -1, fmt.Errorf("Fork failure")
	}

	// handle exception for darwin
	if darwin && ret2 == 1 {
		ret = 0
	}

	// if we got a good PID, then we call exit the parent process.
	if ret > 0 {
		return 0, nil
	}

	// create a new SID for the child process
	s_ret, s_errno := syscall.Setsid()
	if s_errno != nil {
		return -1, fmt.Errorf("Error: syscall.Setsid: %s", s_errno)
	}
	if s_ret < 0 {
		return -1, fmt.Errorf("Error: syscall.Setsid: %s", s_errno)
	}

	if closeno {
		f, e := os.OpenFile("/dev/null", os.O_RDWR, 0)
		if e == nil {
			fd := int(f.Fd())
			syscall.Dup2(fd, int(os.Stdin.Fd()))
			syscall.Dup2(fd, int(os.Stdout.Fd()))
			syscall.Dup2(fd, int(os.Stderr.Fd()))
		}
	}

	return os.Getpid(), nil
}
示例#11
0
文件: log.go 项目: funkygao/gafka
func (this *Start) setupLogging(logFile, logLevel, crashLogFile string) {
	level := log.DEBUG
	switch logLevel {
	case "info":
		level = log.INFO

	case "warn":
		level = log.WARNING

	case "error":
		level = log.ERROR

	case "debug":
		level = log.DEBUG

	case "trace":
		level = log.TRACE

	case "alarm":
		level = log.ALARM
	}

	for _, filter := range log.Global {
		filter.Level = level
	}

	log.LogBufferLength = 32 // default 32, chan cap

	if logFile == "stdout" {
		log.AddFilter("stdout", level, log.NewConsoleLogWriter())
	} else {
		log.DeleteFilter("stdout")

		filer := log.NewFileLogWriter(logFile, true, true, 0)
		filer.SetFormat("[%d %T] [%L] (%S) %M")
		filer.SetRotateSize(0)
		filer.SetRotateLines(0)
		filer.SetRotateDaily(true)
		log.AddFilter("file", level, filer)
	}

	if crashLogFile != "" {
		f, err := os.OpenFile(crashLogFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			panic(err)
		}

		syscall.Dup2(int(f.Fd()), int(os.Stdout.Fd()))
		syscall.Dup2(int(f.Fd()), int(os.Stderr.Fd()))
		fmt.Fprintf(os.Stderr, "\n%s %s (build: %s)\n===================\n",
			time.Now().String(),
			gafka.Version, gafka.BuildId)
	}

}
示例#12
0
func main() {
	var opts Options

	_, err := flags.Parse(&opts)
	if err != nil {
		os.Exit(1)
	}

	if opts.Debug {
		log.SetLevel(log.DebugLevel)
	}

	if opts.LogFile != "" {
		logFp, err := os.OpenFile(opts.LogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
		checkError(fmt.Sprintf("error opening %s", opts.LogFile), err)

		defer logFp.Close()

		// ensure panic output goes to log file
		syscall.Dup2(int(logFp.Fd()), 1)
		syscall.Dup2(int(logFp.Fd()), 2)

		// log as JSON
		log.SetFormatter(&log.JSONFormatter{})

		// send output to file
		log.SetOutput(logFp)
	}

	log.Debug("hi there! (tickertape tickertape)")
	log.Infof("version: %s", version)

	vaultClient, err := helpers.NewVaultClient(opts.VaultAddr, opts.VaultToken)
	checkError("creating Vault client", err)

	consulClient, err := consulapi.NewClient(consulapi.DefaultConfig())
	checkError("creating Consul client", err)

	router := mux.NewRouter()

	registrar := instance.NewRegistrar(vaultClient)
	v1 := v1.NewCentralBooking(
		registrar,
		consulClient.Catalog(),
		vaultClient.GetEndpoint(),
	)
	v1.InstallHandlers(router.PathPrefix("/v1").Subrouter())

	httpServer := &http.Server{
		Addr:    fmt.Sprintf(":%d", opts.HttpPort),
		Handler: Log(router),
	}

	checkError("launching HTTP server", httpServer.ListenAndServe())
}
示例#13
0
// CaptureOutputToFd redirects the current process' stdout and stderr file
// descriptors to the given file descriptor, using the dup2 syscall.
func CaptureOutputToFd(fd int) error {
	err := syscall.Dup2(fd, syscall.Stdout)
	if err != nil {
		return err
	}
	err = syscall.Dup2(fd, syscall.Stderr)
	if err != nil {
		return err
	}
	return nil
}
示例#14
0
func Test_println(t *testing.T) {
	cleanup1 := testutils.Chtemp()
	defer cleanup1()

	rfile, err := os.Create("stdout")
	if err != nil {
		panic(err)
	}

	// save a copy of stdout in another fd
	stdout_fd := int(os.Stdout.Fd())
	save_stdout, err := syscall.Dup(stdout_fd)
	if err != nil {
		panic(err)
	}

	// redirect stdout to rfile
	err = syscall.Dup2(int(rfile.Fd()), stdout_fd)
	if err != nil {
		panic(err)
	}

	cleanup2 := func() {
		rfile.Close()
		err = syscall.Dup2(save_stdout, stdout_fd)
		if err != nil {
			panic(err)
		}
		syscall.Close(save_stdout)
	}
	defer cleanup2()

	args := RuntimeArgs{
		BasicArgs: types.MakeBasicArgs(nil, []types.FuObject{}, nil),
	}

	result, errs := fn_println(args)
	assert.Nil(t, result)
	assert.Equal(t, 0, len(errs))
	data, err := ioutil.ReadFile("stdout")
	assert.Nil(t, err)
	assert.Equal(t, "\n", string(data))
	rfile.Truncate(0)
	rfile.Seek(0, 0)

	args.SetArgs(types.MakeStringList("hello", "world").List())
	fn_println(args)
	data, err = ioutil.ReadFile("stdout")
	assert.Nil(t, err)
	assert.Equal(t, "hello world\n", string(data))
	rfile.Truncate(0)
	rfile.Seek(0, 0)
}
示例#15
0
// detach detaches from the origin stdin/out/err and makes
// sure the CWD is no longer inside the original host rootfs
func Detach(redirectStdout, redirectStderr string) {
	os.Chdir("/")

	devNull := must(os.Open("/dev/null"))
	syscall.Dup2(int(devNull.Fd()), int(os.Stdin.Fd()))

	newStdout := must(os.OpenFile(redirectStdout, os.O_WRONLY|os.O_CREATE, 0700))
	syscall.Dup2(int(newStdout.Fd()), int(os.Stdout.Fd()))

	newStderr := must(os.OpenFile(redirectStderr, os.O_WRONLY|os.O_CREATE, 0700))
	syscall.Dup2(int(newStderr.Fd()), int(os.Stderr.Fd()))
}
示例#16
0
func logRedirectStdOutToFile(logPath string) {
	if logPath == "" {
		Log.Fatal("Log Path not set")
	}

	logFile, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
	if err != nil {
		Log.Fatal(err)
	}
	syscall.Dup2(int(logFile.Fd()), 1)
	syscall.Dup2(int(logFile.Fd()), 2)
}
示例#17
0
文件: main.go 项目: tgres/tgres
func std2DevNull() error {
	f, e := os.OpenFile("/dev/null", os.O_RDWR, 0)
	if e == nil {
		fd := int(f.Fd())
		syscall.Dup2(fd, int(os.Stdin.Fd()))
		syscall.Dup2(fd, int(os.Stdout.Fd()))
		syscall.Dup2(fd, int(os.Stderr.Fd()))
		return nil
	} else {
		return e
	}
}
示例#18
0
文件: relog.go 项目: Eric-Chen/vitess
// Replace stdout and stderr with a file. This overwrites the actual file
// descriptors which means even top level panic output will show up in
// these files.
func HijackStdio(fOut *os.File, fErr *os.File) error {
	if fOut != nil {
		if err := syscall.Dup2(int(fOut.Fd()), int(os.Stdout.Fd())); err != nil {
			return err
		}
	}
	if fErr != nil {
		if err := syscall.Dup2(int(fErr.Fd()), int(os.Stderr.Fd())); err != nil {
			return err
		}
	}
	return nil
}
示例#19
0
func main() {
	logFile, _ := os.OpenFile("/tmp/lrlog", os.O_WRONLY|os.O_CREATE|os.O_SYNC, 0644)
	syscall.Dup2(int(logFile.Fd()), 1)
	syscall.Dup2(int(logFile.Fd()), 2)
	fmt.Printf("Args: %v\n", os.Args[1:])
	pairs := dirsToSync(os.Args[1:])
	for _, p := range pairs {
		sync(p)
	}
	fmt.Printf("reloading...\n")
	start_time := time.Now()
	http.Get("http://icute.local/db/viewer?command=reload")
	fmt.Printf("reloading... %vs\n", time.Since(start_time).Seconds())
}
示例#20
0
文件: main.go 项目: qmdx/mygo
func main() {
	daemon := flag.Bool("daemon", false, "Indicate it's daemon process. Never use it in command line.")
	flag.Parse()

	if *daemon {
		fd, err := syscall.Open("/dev/null", syscall.O_RDWR, 0)

		if err != nil {
			panic(err)
		}

		syscall.Dup2(fd, syscall.Stdin)
		syscall.Dup2(fd, syscall.Stdout)
		syscall.Dup2(fd, syscall.Stderr)

		if fd > syscall.Stderr {
			syscall.Close(fd)
		}
	}

	// start gio as daemon process
	if !*daemon {
		args := append([]string{os.Args[0], "-daemon"}, os.Args[1:]...)
		attr := syscall.ProcAttr{}
		_, _, err := syscall.StartProcess(os.Args[0], args, &attr)

		if err != nil {
			panic(err)
			return
		}
		return
	}

	router := routes.NewRouter()
	for _, function := range functions.Functions {
		router.Get(function.Path, funcwrapper(function.Func))
		router.Post(function.Path, funcwrapper(function.Func))
	}
	s := &http.Server{
		Addr:           ":1234",
		Handler:        router,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	err := s.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}
示例#21
0
func main() {
	// godaemon.MakeDaemon(&godaemon.DaemonAttr{})
	// log.SetFlags(log.Lshortfile)
	layers := os.Args[1]
	mountPoint := os.Args[2]

	// F, err := os.OpenFile("/tmp/constor", os.O_APPEND|os.O_WRONLY, 0)
	// F.Write([]byte("START\n"))
	// F.Write([]byte(layers))
	// F.Write([]byte(" "))
	// F.Write([]byte(mountPoint))
	// F.Write([]byte("\n"))

	if len(os.Args) != 3 {
		fmt.Println("Usage: constor /layer0:/layer1:....:/layerN /mnt/point")
		os.Exit(1)
	}

	pid := os.Getpid()
	pidstr := strconv.Itoa(pid)
	logf, err := os.Create("/tmp/constor.log." + pidstr)
	logfd := logf.Fd()
	syscall.Dup2(int(logfd), 1)
	syscall.Dup2(int(logfd), 2)

	constor := new(Constor)
	constor.inodemap = NewInodemap(constor)
	constor.dentrymap = NewDentrymap(constor)
	constor.fdmap = make(map[uintptr]*FD)
	constor.logf = logf
	constor.layers = strings.Split(layers, ":")
	constor.rootfs = constor.layers[0]

	constor.log("%s %s", layers, mountPoint)

	mOpts := &fuse.MountOptions{
		Name: "constor",
		// SingleThreaded: true,
		Options: []string{"nonempty", "allow_other", "default_permissions", "user_id=0", "group_id=0", "fsname=" + constor.layers[0]},
	}
	_ = syscall.Umask(000)
	state, err := fuse.NewServer(constor, mountPoint, mOpts)
	if err != nil {
		// fmt.Printf("Mount fail: %v\n", err)
		os.Exit(1)
	}
	// fmt.Println("Mounted!")
	state.Serve()
}
示例#22
0
文件: init.go 项目: beibei1990/os
func execDocker(cfg *config.Config) error {
	log.Info("Launching System Docker")
	if !cfg.Debug {
		output, err := os.Create("/var/log/system-docker.log")
		if err != nil {
			return err
		}

		syscall.Dup2(int(output.Fd()), int(os.Stdout.Fd()))
		syscall.Dup2(int(output.Fd()), int(os.Stderr.Fd()))
	}

	os.Stdin.Close()
	return syscall.Exec(SYSTEM_DOCKER, cfg.SystemDocker.Args, os.Environ())
}
示例#23
0
func openOutLog(filename string) *os.File {
	// Move existing out file to a dated file if it exists
	if _, err := os.Stat(filename); err == nil {
		if err = os.Rename(filename, filename+"."+time.Now().Format("2006-01-02_15:04:05")); err != nil {
			log.Criticalf("Cannot move old out file: %v", err)
			os.Exit(1)
		}
	}

	// Redirect stdout and stderr to out file
	logFile, _ := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_SYNC, 0644)
	syscall.Dup2(int(logFile.Fd()), 1)
	syscall.Dup2(int(logFile.Fd()), 2)
	return logFile
}
示例#24
0
文件: daemon.go 项目: shaovie/go
func daemon() error {
	isDarwin := runtime.GOOS == "darwin"

	// already a daemon
	if syscall.Getppid() == 1 {
		return nil
	}

	// fork off the parent process
	ret, ret2, errno := syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0)
	if errno != 0 {
		return errors.New(fmt.Sprintf("fork error! [errno=%d]", errno))
	}

	// failure
	if ret2 < 0 {
		os.Exit(1)
	}

	// handle exception for darwin
	if isDarwin && ret2 == 1 {
		ret = 0
	}

	// if we got a good PID, then we call exit the parent process.
	if int(ret) > 0 {
		os.Exit(0)
	}

	syscall.Umask(0)

	// create a new SID for the child process
	_, err := syscall.Setsid()
	if err != nil {
		return err
	}

	//os.Chdir("/")

	f, err := os.OpenFile("/dev/null", os.O_RDWR, 0)
	if err == nil {
		fd := f.Fd()
		syscall.Dup2(int(fd), int(os.Stdin.Fd()))
		syscall.Dup2(int(fd), int(os.Stdout.Fd()))
		syscall.Dup2(int(fd), int(os.Stderr.Fd()))
	}
	return nil
}
示例#25
0
文件: log.go 项目: cheyang/scloud
func InitLog() error {
	err := os.MkdirAll(logDir, 0644)

	if err != nil {
		return err
	}

	currentTime := time.Now().Unix()

	tm := time.Unix(currentTime, 0)

	timestamp := tm.Format("20060102150405")

	logBaseName := fmt.Sprintf("scloud_%s.log", timestamp)

	logFileName = filepath.Join(logDir, logBaseName)

	logFile, err = os.OpenFile(logFileName, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0664)

	if err != nil {
		return err
	}

	logFile.WriteString(fmt.Sprintf("%v Opened logfile at %v", os.Getpid(), time.Now()))
	os.Stderr = logFile
	syscall.Dup2(int(logFile.Fd()), 2)

	return nil
}
示例#26
0
文件: console.go 项目: NERSC/docker
func OpenAndDup(consolePath string) error {
	slave, err := OpenTerminal(consolePath, syscall.O_RDWR)
	if err != nil {
		return fmt.Errorf("open terminal %s", err)
	}

	if err := syscall.Dup2(int(slave.Fd()), 0); err != nil {
		return err
	}

	if err := syscall.Dup2(int(slave.Fd()), 1); err != nil {
		return err
	}

	return syscall.Dup2(int(slave.Fd()), 2)
}
示例#27
0
func (d *Context) child() (err error) {
	if initialized {
		return os.ErrInvalid
	}
	initialized = true

	decoder := json.NewDecoder(os.Stdin)
	if err = decoder.Decode(d); err != nil {
		return
	}

	if err = syscall.Close(0); err != nil {
		return
	}
	if err = syscall.Dup2(3, 0); err != nil {
		return
	}

	if len(d.PidFileName) > 0 {
		d.pidFile = NewLockFile(os.NewFile(4, d.PidFileName))
		if err = d.pidFile.WritePid(); err != nil {
			return
		}
	}

	if d.Umask != 0 {
		syscall.Umask(int(d.Umask))
	}
	if len(d.Chroot) > 0 {
		err = syscall.Chroot(d.Chroot)
	}

	return
}
示例#28
0
文件: main.go 项目: cookiebus/codis
func setCrashLog(file string) {
	f, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.InfoErrorf(err, "cannot open crash log file: %s", file)
	} else {
		syscall.Dup2(int(f.Fd()), 2)
	}
}
示例#29
0
func CrashLog(file string) {
	f, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.Println(err.Error())
	} else {
		syscall.Dup2(int(f.Fd()), 2)
	}
}
示例#30
0
func init() {
	runtime.GOMAXPROCS(32)
	rand.Seed(time.Now().UnixNano())
	fmt.Printf("")
	flag.Parse()
	// log
	if !*debugFlag {
		_, path, _, _ := runtime.Caller(0)
		logFile, err := os.OpenFile(filepath.Join(filepath.Dir(path), "logs", fmt.Sprintf("%d", time.Now().UnixNano())),
			os.O_WRONLY|os.O_CREATE|os.O_SYNC, 0644)
		if err != nil {
			panic("cannot open log file")
		}
		syscall.Dup2(int(logFile.Fd()), 1)
		syscall.Dup2(int(logFile.Fd()), 2)
	}
}