Golang Signal示例

说明

golang signal示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: syscall

示例#1
文件: daemon.go 项目: WalterShe/wfdr

func main() {
	// Kinda hackish :/
	wd, _ := os.Getwd()
	os.Setenv("PATH",
		path.Join(wd, "framework/bin")+":"+
			path.Join(wd, "framework/sh")+":"+
			os.Getenv("PATH"))

	os.MkdirAll("cache", 0755)

	var inpipe, outpipe, context string

	flag.StringVar(&inpipe, "inpipe", "cache/wfdr-deamon-pipe-in", "Name of a file that should be used for a input IPC pipe. Should not exist.")
	flag.StringVar(&outpipe, "outpipe", "cache/wfdr-deamon-pipe-out", "Name of a file that should be used for an output IPC pipe. Should not exist.")
	flag.StringVar(&context, "context", "debug", "Context to run the daemon and child processes from. Valid choices are 'debug', 'test' and 'prod'.")

	flag.Parse()

	if context != "debug" && context != "test" && context != "prod" {
		log.Println("Invalid context argument provided!")
		log.Fatal(flag.Lookup("context").Usage)
	}

	os.Setenv("WFDR_CONTEXT", context)

	if osutil.FileExists(inpipe) || osutil.FileExists(outpipe) {
		log.Fatal("Pipe files already exist, the daemon is likely already running. However, it is also possible that the daemon was not cleanly shut down on its last run, and the files linger. If you suspect this to be the case, remove cache/wfdr-deamon-pipe-in and cache/wfdr-deamon-pipe-out, then try starting the daemon again.")
	}

	infile, err := moduled.OpenPipe(inpipe)
	if err != nil {
		log.Fatal(err)
	}
	outfile, err := moduled.OpenPipe(outpipe)
	if err != nil {
		log.Fatal(err)
	}

	rwc := &moduled.PipeReadWriteCloser{Input: infile, Output: outfile}

	go monitorPipe(rwc)

	sigc := make(chan os.Signal, 2)
	signal.Notify(sigc, syscall.Signal(0x02), syscall.Signal(0x09), syscall.Signal(0x0f))

	for {
		sig := <-sigc
		switch sig.(syscall.Signal) {
		// SIGINT, SIGKILL, SIGTERM
		case 0x02, 0x09, 0xf:
			Exit(0)
		// SIGCHLD
		case 0x11:
			// Do nothing
		default:
			log.Println(sig)
			break
		}
	}
}

示例#2
文件: cache-monitor.go 项目: WalterShe/wfdr

func (v *Visitor) InotifyLoop() {
	sigc := make(chan os.Signal, 2)
	signal.Notify(sigc, syscall.Signal(0x02), syscall.Signal(0x09), syscall.Signal(0x0f))

	for {
		select {
		case ev := <-v.watcher.Event:
			//os.Exit(0)
			v.WatcherEvent(ev)
		case sig := <-sigc:
			switch sig.(syscall.Signal) {
			// SIGINT, SIGKILL, SIGTERM
			case 0x02, 0x09, 0xf:
				err := v.watcher.Close()
				if err != nil {
					log.Println("Warning: Error closing watcher:", err)
				}
				os.Exit(0)
			// SIGCHLD
			case 0x11:
				// Do nothing
			default:
				log.Println("Unhandled signal:", sig)
			}
		case err := <-v.watcher.Error:
			log.Println("Error in watcher:", err)
		}
	}
}

示例#3
文件: init.go 项目: imjorge/flynn

func (c *ContainerInit) Signal(sig int, res *struct{}) error {
	c.mtx.Lock()
	defer c.mtx.Unlock()
	logger.Info("forwarding signal to job", "type", syscall.Signal(sig))
	if err := c.process.Signal(syscall.Signal(sig)); err != nil {
		return err
	}
	return nil
}

示例#4
文件: signal_handler.go 项目: joseph-hurtado/hostsplitter

func SignalHandler() {
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.Signal(0xa))
	for {
		if <-sigs == syscall.Signal(0xa) {
			log.Print("Recieved 0xa, reloading config")
			LoadConfig()
		}
	}
}

示例#5
文件: signal_handler.go 项目: ammario/hostsplitter

func init() {
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.Signal(0xa))
	go func() {
		for syscall.Signal(0xa) == <-sigs {
			log.Print("Recieved 0xa, reloading config")
			LoadConfig()
		}
	}()

}

示例#6
文件: execution_unix.go 项目: echocat/caretakerd

func sendSignalToProcess(process *os.Process, what values.Signal, tryGroup bool) error {
	if tryGroup {
		pgid, err := syscall.Getpgid(process.Pid)
		if err == nil {
			if syscall.Kill(-pgid, syscall.Signal(what)) == nil {
				return nil
			}
		}
	}
	process.Signal(syscall.Signal(what))
	return nil
}

示例#7
文件: ioutil.go 项目: dhiltgen/ioutil

func validateBackend(dirname string, interval int) error {
	_, err := os.Stat(path.Join(dirname, DataFilename))
	// TODO Handle perm problems...
	if err != nil {
		//log.Println("XXX Failed stat")
		return start(dirname, interval)
	}

	// Data file exists, now check for the pid
	data, err := ioutil.ReadFile(path.Join(dirname, PidFilename))
	if err != nil {
		//log.Println("XXX Failed pid read")
		return start(dirname, interval)
	}
	pidString := strings.TrimSpace(string(data))
	pid, err := strconv.Atoi(pidString)
	if err != nil {
		//log.Println("XXX Failed conversion on pid")
		return start(dirname, interval)
	}
	process, err := os.FindProcess(pid)
	if err != nil {
		//log.Println("XXX Failed process find")
		return start(dirname, interval)
	}
	if err := process.Signal(syscall.Signal(0)); err != nil {
		return start(dirname, interval)
	}

	// Validate the interval is the right
	data, err = ioutil.ReadFile(path.Join(dirname, IntervalFilename))
	if err != nil {
		//log.Println("XXX Failed interval read")
		process.Signal(syscall.Signal(9))
		return start(dirname, interval)
	}

	oldIntervalString := strings.TrimSpace(string(data))
	oldInterval, err := strconv.Atoi(oldIntervalString)
	if err != nil {
		//log.Println("XXX Failed process interval")
		process.Signal(syscall.Signal(9))
		return start(dirname, interval)
	}
	if oldInterval != interval {
		//log.Println("XXX wrong interval")
		process.Signal(syscall.Signal(9))
		return start(dirname, interval)
	}

	// Everything looks good, continue using it
	return nil
}

示例#8
文件: utils.go 项目: jmptrader/spirit

func isProcessAlive(pid int) bool {
	p, _ := os.FindProcess(pid)
	if e := p.Signal(syscall.Signal(0)); e == nil {
		return true
	}
	return false
}

示例#9
文件: ptrace_test.go 项目: hjr265/ptrace.go

func TestSyscall(t *testing.T) {
	proc, err := os.StartProcess("/usr/bin/ls", []string{"ls", "/"}, &os.ProcAttr{
		Sys: &syscall.SysProcAttr{
			Ptrace: true,
		},
	})
	catch(err)

	time.Sleep(1 * time.Nanosecond)

	tracer, err := Attach(proc)
	catch(err)

	for {
		no, err := tracer.Syscall(syscall.Signal(0))
		if err == syscall.ESRCH {
			t.Logf("Syscall() threw %v", err)
			break
		}
		if err != nil {
			t.Errorf("Syscall() threw %v", err)
			break
		}

		t.Logf("Syscall() = %v", no)
	}
}

示例#10
文件: hive.go 项目: rprp/hivego

func checkAndSetPid(pidFile string) error { // {{{
	contents, err := ioutil.ReadFile(pidFile)
	if err == nil {
		pid, err := strconv.Atoi(strings.TrimSpace(string(contents)))
		if err != nil {
			return errors.New(fmt.Sprintf("Error reading proccess id from pidfile '%s': %s", pidFile, err))
		}

		process, err := os.FindProcess(pid)

		// on Windows, err != nil if the process cannot be found
		if runtime.GOOS == "windows" {
			if err == nil {
				return errors.New(fmt.Sprintf("Process %d is already running.", pid))
			}
		} else if process != nil {
			// err is always nil on POSIX, so we have to send the process a signal to check whether it exists
			if err = process.Signal(syscall.Signal(0)); err == nil {
				return errors.New(fmt.Sprintf("Process %d is already running.", pid))
			}
		}
	}
	if err := ioutil.WriteFile(pidFile, []byte(strconv.Itoa(os.Getpid())), 0644); err != nil {
		return errors.New(fmt.Sprintf("Unable to write pidfile '%s': %s", pidFile, err))
	}
	log.Printf("Wrote pid to pidfile '%s'", pidFile)

	return nil
} // }}}

示例#11
文件: zork.go 项目: A-t48/frotz-slack-bot

func (z *Zork) Close() error {
	// Signal 0 checks if the process is alive.
	if z.cmd.Process.Signal(syscall.Signal(0)) == nil {
		return z.cmd.Process.Kill()
	}
	return nil
}

示例#12
文件: client_windows.go 项目: RAMESHBABUK/docker

// Signal handles `docker stop` on Windows. While Linux has support for
// the full range of signals, signals aren't really implemented on Windows.
// We fake supporting regular stop and -9 to force kill.
func (clnt *client) Signal(containerID string, sig int) error {
	var (
		cont *container
		err  error
	)

	// Get the container as we need it to find the pid of the process.
	clnt.lock(containerID)
	defer clnt.unlock(containerID)
	if cont, err = clnt.getContainer(containerID); err != nil {
		return err
	}

	cont.manualStopRequested = true

	logrus.Debugf("lcd: Signal() containerID=%s sig=%d pid=%d", containerID, sig, cont.systemPid)
	context := fmt.Sprintf("Signal: sig=%d pid=%d", sig, cont.systemPid)

	if syscall.Signal(sig) == syscall.SIGKILL {
		// Terminate the compute system
		if err := hcsshim.TerminateComputeSystem(containerID, hcsshim.TimeoutInfinite, context); err != nil {
			logrus.Errorf("Failed to terminate %s - %q", containerID, err)
		}
	} else {
		// Terminate Process
		if err = hcsshim.TerminateProcessInComputeSystem(containerID, cont.systemPid); err != nil {
			logrus.Warnf("Failed to terminate pid %d in %s: %q", cont.systemPid, containerID, err)
			// Ignore errors
			err = nil
		}
	}

	return nil
}

示例#13
文件: driver.go 项目: colebrumley/docker

func (d *driver) Kill(c *execdriver.Command, sig int) error {
	if sig == 9 || c.ProcessConfig.Process == nil {
		return KillLxc(c.ID, sig)
	}

	return c.ProcessConfig.Process.Signal(syscall.Signal(sig))
}

示例#14
文件: runner.go 项目: tkysk/consul-release

func (r *Runner) Stop() error {
	r.Logger.Info("agent-runner.stop.get-process")

	process, err := r.getProcess()
	if err != nil {
		r.Logger.Error("agent-runner.stop.get-process.failed", errors.New(err.Error()))
		return err
	}

	r.Logger.Info("agent-runner.stop.get-process.result", lager.Data{
		"pid": process.Pid,
	})

	r.Logger.Info("agent-runner.stop.signal", lager.Data{
		"pid": process.Pid,
	})

	err = process.Signal(syscall.Signal(syscall.SIGKILL))
	if err != nil {
		r.Logger.Error("agent-runner.stop.signal.failed", err)
		return err
	}

	r.Logger.Info("agent-runner.stop.success")
	return nil
}

示例#15
文件: proc_container.go 项目: topfreegames/apm

// IsAlive will check if the process is alive or not.
// Returns true if the process is alive or false otherwise.
func (proc *Proc) IsAlive() bool {
	p, err := os.FindProcess(proc.Pid)
	if err != nil {
		return false
	}
	return p.Signal(syscall.Signal(0)) == nil
}

示例#16
文件: client_context.go 项目: ikbear/gotty

func (context *clientContext) goHandleClient() {
	exit := make(chan bool, 2)

	go func() {
		defer func() { exit <- true }()

		context.processSend()
	}()

	go func() {
		defer func() { exit <- true }()

		context.processReceive()
	}()

	go func() {
		defer context.app.server.FinishRoutine()

		<-exit
		context.pty.Close()

		// Even if the PTY has been closed,
		// Read(0 in processSend() keeps blocking and the process doen't exit
		context.command.Process.Signal(syscall.Signal(context.app.options.CloseSignal))

		context.command.Wait()
		context.connection.Close()
		log.Printf("Connection closed: %s", context.request.RemoteAddr)
	}()
}

示例#17
文件: runner.go 项目: tkysk/consul-release

func (r *Runner) Wait() error {
	r.Logger.Info("agent-runner.wait.get-process")

	process, err := r.getProcess()
	if err != nil {
		r.Logger.Error("agent-runner.wait.get-process.failed", errors.New(err.Error()))
		return err
	}

	r.Logger.Info("agent-runner.wait.get-process.result", lager.Data{
		"pid": process.Pid,
	})

	r.Logger.Info("agent-runner.wait.signal", lager.Data{
		"pid": process.Pid,
	})

	for {
		err = process.Signal(syscall.Signal(0))
		if err == nil {
			time.Sleep(10 * time.Millisecond)
			continue
		}

		break
	}

	r.Logger.Info("agent-runner.wait.success")
	return nil
}

示例#18
文件: toolbox.go 项目: vmware/vic

func (t *Toolbox) killHelper(session *SessionConfig, name string) error {
	if name == "" {
		name = string(ssh.SIGTERM)
	}

	if session.Cmd.Process == nil {
		return fmt.Errorf("the session %s hasn't launched yet", session.ID)
	}

	sig := new(msgs.SignalMsg)
	err := sig.FromString(name)
	if err != nil {
		return err
	}

	num := syscall.Signal(sig.Signum())

	log.Infof("sending signal %s (%d) to %s", sig.Signal, num, session.ID)

	if err := session.Cmd.Process.Signal(num); err != nil {
		return fmt.Errorf("failed to signal %s: %s", session.ID, err)
	}

	return nil
}

示例#19
文件: context.go 项目: elliotcm/webrocket

// Lock creates a lockfile which prevents to open more than one instance
// of the same node (on the same machine).
func (ctx *Context) Lock() (err error) {
	var f *os.File
	var p *os.Process
	var pid int

	lockFile := path.Join(ctx.storageDir, ctx.nodeName+".lock")
	if f, err = os.Open(lockFile); err != nil {
		goto lock
	}
	if _, err = fmt.Fscanf(f, "%d", &pid); err != nil && pid == 0 {
		goto lock
	}
	if p, err = os.FindProcess(pid); err == nil && p != nil {
		if err = p.Signal(syscall.Signal(0)); err == nil {
			msg := fmt.Sprintf("node '%s' is already running", ctx.NodeName())
			return errors.New(msg)
		}
	}
lock:
	// Write a lock file.
	pidstr := []byte(fmt.Sprintf("%d", os.Getppid()))
	if err = ioutil.WriteFile(lockFile, pidstr, 0644); err != nil {
		return
	}
	return nil
}

示例#20
文件: http.go 项目: hSATAC/grace

// Used for checking if a process exists in pidfile
func processExistsAtPidString(pidStr string) bool {
	// Check if the process exists
	pid, err := strconv.Atoi(pidStr)
	if err != nil {
		return true // Convert error, can't determine.
	}

	process, err := os.FindProcess(pid)
	if err != nil {
		return true
	}

	err = process.Signal(os.Signal(syscall.Signal(0)))

	if err == nil {
		return true
	}

	errno, ok := err.(syscall.Errno)
	if !ok {
		return false
	}

	switch errno {
	case syscall.ESRCH:
		return false // Only here we could be sure the process does not exist.
	case syscall.EPERM:
		return true
	}

	return true
}

示例#21
文件: apm.go 项目: topfreegames/apm

func stopRemoteMasterServer() {
	if *serveStopConfigFile == "" {
		folderPath, err := osext.ExecutableFolder()
		if err != nil {
			log.Fatal(err)
		}
		*serveStopConfigFile = folderPath + "/.apmenv/config.toml"
		os.MkdirAll(path.Dir(*serveStopConfigFile), 0777)
	}
	ctx := &daemon.Context{
		PidFileName: path.Join(filepath.Dir(*serveStopConfigFile), "main.pid"),
		PidFilePerm: 0644,
		LogFileName: path.Join(filepath.Dir(*serveStopConfigFile), "main.log"),
		LogFilePerm: 0640,
		WorkDir:     "./",
		Umask:       027,
	}

	if ok, p, _ := isDaemonRunning(ctx); ok {
		if err := p.Signal(syscall.Signal(syscall.SIGQUIT)); err != nil {
			log.Fatalf("Failed to kill daemon %v", err)
		}
	} else {
		ctx.Release()
		log.Info("instance is not running.")
	}
}

示例#22
文件: attach_linux.go 项目: kjplatz/vic

func signalProcess(process *os.Process, sig ssh.Signal) error {
	signal := msgs.Signals[sig]
	defer trace.End(trace.Begin(fmt.Sprintf("signal process %d: %s", process.Pid, sig)))

	s := syscall.Signal(signal)
	return process.Signal(s)
}

示例#23
文件: exec_cmd_runner.go 项目: vestel/bosh-init

func (p *execProcess) groupExists() bool {
	err := syscall.Kill(-p.pid, syscall.Signal(0))
	if p.isGroupDoesNotExistError(err) {
		return false
	}
	return true
}

示例#24
文件: posix_test.go 项目: 2thetop/go

func isProcessRunning(t *testing.T, pid int) bool {
	p, err := os.FindProcess(pid)
	if err != nil {
		return false
	}
	return p.Signal(syscall.Signal(0)) == nil
}

示例#25
文件: kill.go 项目: hallyn/docker

// ContainerKill send signal to the container
// If no signal is given (sig 0), then Kill with SIGKILL and wait
// for the container to exit.
// If a signal is given, then just send it to the container and return.
func (daemon *Daemon) ContainerKill(name string, sig uint64) error {
	container, err := daemon.GetContainer(name)
	if err != nil {
		return err
	}

	if sig != 0 && !signal.ValidSignalForPlatform(syscall.Signal(sig)) {
		return fmt.Errorf("The %s daemon does not support signal %d", runtime.GOOS, sig)
	}

	// If no signal is passed, or SIGKILL, perform regular Kill (SIGKILL + wait())
	if sig == 0 || syscall.Signal(sig) == syscall.SIGKILL {
		return daemon.Kill(container)
	}
	return daemon.killWithSignal(container, int(sig))
}

示例#26
文件: exec_test.go 项目: dgshep/nomad

func TestExecDriver_KillUserPid_OnPluginReconnectFailure(t *testing.T) {
	t.Parallel()
	ctestutils.ExecCompatible(t)
	task := &structs.Task{
		Name: "sleep",
		Config: map[string]interface{}{
			"command": "/bin/sleep",
			"args":    []string{"1000000"},
		},
		LogConfig: &structs.LogConfig{
			MaxFiles:      10,
			MaxFileSizeMB: 10,
		},
		Resources: basicResources,
	}

	driverCtx, execCtx := testDriverContexts(task)
	defer execCtx.AllocDir.Destroy()
	d := NewExecDriver(driverCtx)

	handle, err := d.Start(execCtx, task)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	if handle == nil {
		t.Fatalf("missing handle")
	}
	defer handle.Kill()

	id := &execId{}
	if err := json.Unmarshal([]byte(handle.ID()), id); err != nil {
		t.Fatalf("Failed to parse handle '%s': %v", handle.ID(), err)
	}
	pluginPid := id.PluginConfig.Pid
	proc, err := os.FindProcess(pluginPid)
	if err != nil {
		t.Fatalf("can't find plugin pid: %v", pluginPid)
	}
	if err := proc.Kill(); err != nil {
		t.Fatalf("can't kill plugin pid: %v", err)
	}

	// Attempt to open
	handle2, err := d.Open(execCtx, handle.ID())
	if err == nil {
		t.Fatalf("expected error")
	}
	if handle2 != nil {
		handle2.Kill()
		t.Fatalf("expected handle2 to be nil")
	}
	// Test if the userpid is still present
	userProc, err := os.FindProcess(id.UserPid)

	err = userProc.Signal(syscall.Signal(0))

	if err == nil {
		t.Fatalf("expected user process to die")
	}
}

示例#27
文件: syscall_solaris.go 项目: CliffYuan/etcd

func (w WaitStatus) Signal() syscall.Signal {
	sig := syscall.Signal(w & mask)
	if sig == stopped || sig == 0 {
		return -1
	}
	return sig
}

示例#28
文件: executor_plugin.go 项目: nak3/nomad

// Registering these types since we have to serialize and de-serialize the Task
// structs over the wire between drivers and the executor.
func init() {
	gob.Register([]interface{}{})
	gob.Register(map[string]interface{}{})
	gob.Register([]map[string]string{})
	gob.Register([]map[string]int{})
	gob.Register(syscall.Signal(0x1))
}

示例#29
文件: client_windows.go 项目: kasisnu/docker

// Signal handles `docker stop` on Windows. While Linux has support for
// the full range of signals, signals aren't really implemented on Windows.
// We fake supporting regular stop and -9 to force kill.
func (clnt *client) Signal(containerID string, sig int) error {
	var (
		cont *container
		err  error
	)

	// Get the container as we need it to get the container handle.
	clnt.lock(containerID)
	defer clnt.unlock(containerID)
	if cont, err = clnt.getContainer(containerID); err != nil {
		return err
	}

	cont.manualStopRequested = true

	logrus.Debugf("libcontainerd: Signal() containerID=%s sig=%d pid=%d", containerID, sig, cont.systemPid)

	if syscall.Signal(sig) == syscall.SIGKILL {
		// Terminate the compute system
		if err := cont.hcsContainer.Terminate(); err != nil {
			if !hcsshim.IsPending(err) {
				logrus.Errorf("libcontainerd: failed to terminate %s - %q", containerID, err)
			}
		}
	} else {
		// Terminate Process
		if err := cont.hcsProcess.Kill(); err != nil && !hcsshim.IsAlreadyStopped(err) {
			// ignore errors
			logrus.Warnf("libcontainerd: failed to terminate pid %d in %s: %q", cont.systemPid, containerID, err)
		}
	}

	return nil
}

示例#30
文件: reload.go 项目: ZhangTingkuo/im_service

func getInitListener(laddr string) (net.Listener, error) {
	var l net.Listener
	var err error
	listenerWaitGroup.Add(1)

	graceful := os.Getenv(Graceful)
	if graceful != "" {
		signal, err := strconv.Atoi(graceful)
		if err != nil {
			log.Infof("%s get singal %s fail: %v", laddr, graceful, err)
		}
		sig := syscall.Signal(signal)
		switch sig {
		case syscall.SIGHUP:
			// get current file descriptor
			currFdStr := os.Getenv(laddr)
			currFd, err := strconv.Atoi(currFdStr)
			if err != nil {
				log.Info("%s get fd fail: %v", laddr, err)
			}
			log.Infof("main: %s Listening to existing file descriptor %v.", laddr, currFd)
			f := os.NewFile(uintptr(currFd), "")
			// file listener dup fd
			l, err = net.FileListener(f)
			// close current file descriptor
			f.Close()
		default:
			log.Infof("%s get singal %s fail: no thing to do", laddr, graceful)
		}
	} else {
		log.Infof("listen to %s.", laddr)
		l, err = net.Listen("tcp", laddr)
	}
	return l, err
}

展开阅读全文