golang 消息忽略 signal.Ignore(syscall.SIGHUP) 示例

  • Post author:
  • Post category:golang



目录


示例1: exec.Command 子进程调用 忽略消息 防止僵尸进程


示例2:管道调用中的 消息忽略


示例3:多个消息忽略


示例4:消息忽略 与 消息处理 同存


消息具体含义参考:

《golang signal 信号处理》

https://blog.csdn.net/whatday/article/details/118650161

示例1: exec.Command 子进程调用 忽略消息 防止僵尸进程

func main() {
	flag.Usage = usage
	flag.Parse()
	if flag.NArg() < 1 {
		usage()
	}

	if isatty(1) {
		dofile()
	}

	if isatty(2) {
		os.Stderr = os.Stdout
	}

	signal.Ignore(syscall.SIGHUP)

	args := flag.Args()
	cmd := exec.Command(args[0], args[1:]...)
	cmd.Stdin = os.Stdin
	cmd.Stderr = os.Stderr
	cmd.Stdout = os.Stdout

	err := cmd.Run()
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		if _, ok := err.(*exec.ExitError); ok {
			os.Exit(126)
		}
		os.Exit(127)
	}
}

示例2:管道调用中的 消息忽略

func childMain() error {
	var err error

	pipe := os.NewFile(uintptr(3), "pipe")
	if pipe != nil {
		defer pipe.Close()
		if err == nil {
			pipe.Write([]byte{DaemonSuccess})
		} else {
			pipe.Write([]byte{DaemonFailure})
		}
	}

	signal.Ignore(syscall.SIGCHLD)

	syscall.Close(0)
	syscall.Close(1)
	syscall.Close(2)

	syscall.Setsid()
	syscall.Umask(022)

	// syscall.Chdir("/")

	return nil
}

示例3:多个消息忽略

func InitSignalHandling() {
	signal.Ignore(syscall.SIGTTOU, syscall.SIGTTIN)

	signals := []os.Signal{syscall.SIGINT, syscall.SIGTSTP}
	incoming = make(chan os.Signal, len(signals))

	signal.Notify(incoming, signals...)

	go broker()
}

示例4:消息忽略 与 消息处理 同存

func OnInterrupt(fn func(), onExitFunc func()) {
	// deal with control+c,etc
	signalChan := make(chan os.Signal, 1)
	// controlling terminal close, daemon not exit
	signal.Ignore(syscall.SIGHUP)
	signal.Notify(signalChan,
		os.Interrupt,
		os.Kill,
		syscall.SIGALRM,
		// syscall.SIGHUP,
		// syscall.SIGINFO, this causes windows to fail
		syscall.SIGINT,
		syscall.SIGTERM,
		// syscall.SIGQUIT, // Quit from keyboard, "kill -3"
	)
	go func() {
		for _ = range signalChan {
			fn()
			if onExitFunc != nil {
				onExitFunc()
			}
			os.Exit(0)
		}
	}()
}



版权声明:本文为whatday原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。