当前位置: 首页>>代码示例>>Golang>>正文


Golang syscall.Kill函数代码示例

本文整理汇总了Golang中syscall.Kill函数的典型用法代码示例。如果您正苦于以下问题:Golang Kill函数的具体用法?Golang Kill怎么用?Golang Kill使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Kill函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: kill

func (c *command) kill() {
	// We started the process in its own process group and now kill the whole group.
	// This solves a potential problem with strace:
	// if we kill just strace, executor still runs and ReadAll below hangs.
	syscall.Kill(-c.cmd.Process.Pid, syscall.SIGKILL)
	syscall.Kill(c.cmd.Process.Pid, syscall.SIGKILL)
}
开发者ID:reidwooten99apps,项目名称:syzkaller,代码行数:7,代码来源:ipc.go

示例2: cleanupProcessGroup

func (c *Cmd) cleanupProcessGroup() {
	if !c.started {
		return
	}
	c.cleanupMu.Lock()
	defer c.cleanupMu.Unlock()

	if c.calledCleanup {
		return
	}
	c.calledCleanup = true

	// Send SIGINT first; then, after a grace period, send SIGKILL to any
	// process that is still running.
	if err := syscall.Kill(-c.Pid(), syscall.SIGINT); err == syscall.ESRCH {
		return
	}
	for i := 0; i < 10; i++ {
		time.Sleep(100 * time.Millisecond)
		if err := syscall.Kill(-c.Pid(), 0); err == syscall.ESRCH {
			return
		}
	}
	syscall.Kill(-c.Pid(), syscall.SIGKILL)
}
开发者ID:asadovsky,项目名称:gosh,代码行数:25,代码来源:cmd.go

示例3: Cleanup

func (r *remote) Cleanup() {
	if r.daemonPid == -1 {
		return
	}
	r.rpcConn.Close()
	// Ask the daemon to quit
	syscall.Kill(r.daemonPid, syscall.SIGTERM)

	// Wait up to 15secs for it to stop
	for i := time.Duration(0); i < containerdShutdownTimeout; i += time.Second {
		if !utils.IsProcessAlive(r.daemonPid) {
			break
		}
		time.Sleep(time.Second)
	}

	if utils.IsProcessAlive(r.daemonPid) {
		logrus.Warnf("libcontainerd: containerd (%d) didn't stop within 15 secs, killing it\n", r.daemonPid)
		syscall.Kill(r.daemonPid, syscall.SIGKILL)
	}

	// cleanup some files
	os.Remove(filepath.Join(r.stateDir, containerdPidFilename))
	os.Remove(filepath.Join(r.stateDir, containerdSockFilename))
}
开发者ID:ungureanuvladvictor,项目名称:docker,代码行数:25,代码来源:remote_linux.go

示例4: TestServerWithBasicAuth

func TestServerWithBasicAuth(t *testing.T) {
	cmd := exec.Cmd{
		Path: os.Getenv("GOPATH") + "/bin/docker-builder",
		Args: []string{"docker-builder", "serve", "--username", "foo", "--password", "bar"},
	}
	if err := cmd.Start(); err != nil {
		t.Errorf("error start server: %s\n", err.Error())
	}

	go func() {
		time.Sleep(100 * time.Millisecond)
		syscall.Kill(cmd.Process.Pid, syscall.SIGUSR1)
		time.Sleep(100 * time.Millisecond)
		syscall.Kill(cmd.Process.Pid, syscall.SIGTERM)
	}()

	if err := cmd.Wait(); err != nil {
		if exiterr, ok := err.(*exec.ExitError); ok {
			if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
				if status.ExitStatus() != 166 {
					t.Errorf("server exited unexpectedly and/or did not start correctly")
				}
			} else {
				t.Errorf("unable to get process exit code")
			}
		} else {
			t.Errorf("error waiting on server: %s\n", err.Error())
		}
	}
}
开发者ID:carriercomm,项目名称:docker-builder,代码行数:30,代码来源:integration_test.go

示例5: TestDeath

func TestDeath(t *testing.T) {
	defer log.Flush()

	Convey("Validate death happens cleanly", t, func() {
		death := NewDeath(syscall.SIGTERM)
		syscall.Kill(os.Getpid(), syscall.SIGTERM)
		death.WaitForDeath()

	})

	Convey("Validate death happens with other signals", t, func() {
		death := NewDeath(syscall.SIGHUP)
		closeMe := &CloseMe{}
		syscall.Kill(os.Getpid(), syscall.SIGHUP)
		death.WaitForDeath(closeMe)
		So(closeMe.Closed, ShouldEqual, 1)
	})

	Convey("Validate death gives up after timeout", t, func() {
		death := NewDeath(syscall.SIGHUP)
		death.setTimeout(10 * time.Millisecond)
		neverClose := &neverClose{}
		syscall.Kill(os.Getpid(), syscall.SIGHUP)
		death.WaitForDeath(neverClose)

	})

}
开发者ID:Fresheyeball,项目名称:death,代码行数:28,代码来源:death_unix_test.go

示例6: TestSighupHandler

func TestSighupHandler(t *testing.T) {
	ranHandler := make(chan bool, 1)
	handler := func(d daemon.Daemon) {
		ranHandler <- true
	}
	conf, _ := config.New("example.yaml")
	d, _ := daemon.New(conf)
	setupSighupHandler(d, handler)
	// Need to sleep here so that the goroutine has time to set up the signal listener, otherwise
	// the signal gets missed
	time.Sleep(1 * time.Second)
	syscall.Kill(syscall.Getpid(), syscall.SIGHUP)

	// Give the syscall 1 second to be handled, should be more than enough time
	timeout := make(chan bool, 1)
	go func() {
		time.Sleep(time.Duration(1 * time.Second))
		timeout <- true
	}()
	select {
	case <-ranHandler:
	case <-timeout:
		t.Fatal("Didn't run handler")
	}

	// Try calling again and make sure it still happens
	syscall.Kill(syscall.Getpid(), syscall.SIGHUP)
	select {
	case <-ranHandler:
	case <-timeout:
		t.Fatal("Didn't run handler second time")
	}
}
开发者ID:Clever,项目名称:sphinx,代码行数:33,代码来源:main_test.go

示例7: TestSignal

// Test that basic signal handling works.
func TestSignal(t *testing.T) {
	// Ask for SIGHUP
	c := make(chan os.Signal, 1)
	Notify(c, syscall.SIGHUP)
	defer Stop(c)

	// Send this process a SIGHUP
	t.Logf("sighup...")
	syscall.Kill(syscall.Getpid(), syscall.SIGHUP)
	waitSig(t, c, syscall.SIGHUP)

	// Ask for everything we can get.
	c1 := make(chan os.Signal, 1)
	Notify(c1)

	// Send this process a SIGWINCH
	t.Logf("sigwinch...")
	syscall.Kill(syscall.Getpid(), syscall.SIGWINCH)
	waitSig(t, c1, syscall.SIGWINCH)

	// Send two more SIGHUPs, to make sure that
	// they get delivered on c1 and that not reading
	// from c does not block everything.
	t.Logf("sighup...")
	syscall.Kill(syscall.Getpid(), syscall.SIGHUP)
	waitSig(t, c1, syscall.SIGHUP)
	t.Logf("sighup...")
	syscall.Kill(syscall.Getpid(), syscall.SIGHUP)
	waitSig(t, c1, syscall.SIGHUP)

	// The first SIGHUP should be waiting for us on c.
	waitSig(t, c, syscall.SIGHUP)
}
开发者ID:Xiahl1990,项目名称:go,代码行数:34,代码来源:signal_test.go

示例8: stop

// stop attempts to stop the process, first with SIGTERM, then if the process
// is still running after KILLPAUSE nanoseconds with SIGKILL. It returns the
// Waitmsg generated when the process died.
func (kp *KickitProcess) stop() (msg *os.Waitmsg, err os.Error) {
	kp.wantDown = true

	if kp.process == nil {
		return nil, ErrNotRunning
	}

	// If an error occurs here it indicates the process already died. This
	// is fine, as it means a Waitmsg is waiting for us when we hit the select
	syscall.Kill(kp.process.Pid, syscall.SIGTERM)

	// Give the process KILLPAUSE ns to die
	timer := time.NewTimer(KILLPAUSE)
	select {
	case msg = <-kp.waitChan:
		timer.Stop()
		log.Printf("%s stopped\n", kp.name)
		kp.process = nil
		return msg, nil

	case <-timer.C:
	}

	// Same situation, an error means the process already died - its ok
	syscall.Kill(kp.process.Pid, syscall.SIGKILL)
	msg = <-kp.waitChan
	log.Printf("%s stopped\n", kp.name)
	kp.process = nil
	return msg, nil
}
开发者ID:cloudkick,项目名称:kickit,代码行数:33,代码来源:process.go

示例9: TestSameProcessLock

func TestSameProcessLock(t *testing.T) {
	lock, err := New("/tmp/lockfile.smaeprocess.lock")
	assert := assert.New(t)
	if os.Getenv("PARENTPID") == "" {
		//parent
		os.Setenv("PARENTPID", strconv.Itoa(os.Getpid()))
		cmd := exec.Command(os.Args[0], os.Args[1:]...)
		cmd.Env = os.Environ()
		cmd.Stdin = os.Stdin
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		cmd.Start()
		c := make(chan os.Signal, 1)
		signal.Notify(c, syscall.SIGUSR1)
		<-c
		assert.NotNil(lock.TryLock())
		syscall.Kill(cmd.Process.Pid, syscall.SIGUSR1)
		cmd.Wait()
		assert.Nil(lock.TryLock())
		assert.Nil(lock.TryLock())
	} else {
		//child
		c := make(chan os.Signal, 1)
		signal.Notify(c, syscall.SIGUSR1)
		ppid, _ := strconv.Atoi(os.Getenv("PARENTPID"))
		assert.Nil(err)
		assert.Nil(lock.TryLock())
		syscall.Kill(ppid, syscall.SIGUSR1)
		<-c
	}
}
开发者ID:eleme,项目名称:lockfile,代码行数:31,代码来源:lockfile_test.go

示例10: scheduleTermination

// scheduleTermination schedules termination with sigterm
// of a previous haproxy instance after configured amount of time
func (c *HaproxyConfigurator) scheduleTermination(pid int) {
	log.Printf("scheduling termination for haproxy with pid %d in %s\n", pid, c.timeout)
	deadline := time.Now().Add(c.timeout)

	go func() {
		for {
			err := syscall.Kill(pid, 0)
			if err != nil {
				if err == syscall.ESRCH {
					log.Printf("haproxy with pid %d gracefully exited before we killed it\n", pid)
				} else {
					log.Println("error checking that haproxy with pid %d is still running: %s\n", pid, err)
				}

				break
			}

			if time.Now().After(deadline) {
				log.Printf("killing haproxy with pid %d with sigterm\n", pid)
				err := syscall.Kill(pid, syscall.SIGTERM)
				if err != nil {
					log.Printf("error killing haproxy with pid %d: %s\n", pid, err)
				}

				break
			}

			time.Sleep(time.Second)
		}
	}()
}
开发者ID:wangfakang,项目名称:marathoner,代码行数:33,代码来源:haproxy.go

示例11: Reap

// Called on running checks, to determine if they have finished
// running.
//
// If the Check has not finished executing, returns false.
//
// If the Check has been running for longer than its Timeout,
// a SIGTERM (and failing that a SIGKILL) is issued to forcibly
// terminate the rogue Check process. In either case, this returns
// as if the check has not yet finished, and Reap() will need to be
// called again to fully reap the Check
//
// If the Check has finished execution (on its own, or via forced
// termination), it will return true.
//
// Once complete, some additional meta-stats for the check execution
// are appended to the check output, to be submit up to bolo
func (self *Check) Reap() bool {
	pid := self.process.Process.Pid

	var ws syscall.WaitStatus
	status, err := syscall.Wait4(pid, &ws, syscall.WNOHANG, nil)
	if err != nil {
		log.Error("Error waiting on check %s[%d]: %s", self.Name, pid, err.Error())
		return false
	}
	if status == 0 {
		// self to see if we need to sigkill due to failed sigterm
		if time.Now().After(self.started_at.Add(time.Duration(self.Timeout+2) * time.Second)) {
			log.Warn("Check %s[%d] has been running too long, sending SIGKILL", self.Name, pid)
			if err := syscall.Kill(pid, syscall.SIGKILL); err != nil {
				log.Error("Error sending SIGKILL to check %s[%d]: %s", self.Name, pid, err.Error())
			}
			self.sig_kill = true
		}
		// self to see if we need to sigterm due to self timeout expiry
		if !self.sig_kill && time.Now().After(self.started_at.Add(time.Duration(self.Timeout)*time.Second)) {
			log.Warn("Check %s[%d] has been running too long, sending SIGTERM", self.Name, pid)
			if err := syscall.Kill(pid, syscall.SIGTERM); err != nil {
				log.Error("Error sending SIGTERM to check %s[%d]: %s", self.Name, pid, err.Error())
			}
			self.sig_term = true
		}
		return false
	}

	self.ended_at = time.Now()
	self.running = false
	self.duration = time.Since(self.started_at)
	self.latency = self.started_at.Sub(self.next_run)
	self.output = string(self.stdout.Bytes())
	self.err_msg = string(self.stderr.Bytes())

	if ws.Exited() {
		self.rc = ws.ExitStatus()
	} else {
		log.Debug("Check %s[%d] exited abnormally (signaled/stopped). Setting rc to UNKNOWN", self.Name, pid)
		self.rc = UNKNOWN
	}
	if self.rc > UNKNOWN {
		log.Debug("Check %s[%d] returned with an invalid exit code. Setting rc to UNKOWN", self.Name, pid)
		self.rc = UNKNOWN
	}

	self.reschedule()

	if self.ended_at.After(self.next_run) {
		timeout_triggered := "not reached"
		if self.sig_term || self.sig_kill {
			timeout_triggered = "reached"
		}
		log.Warn("Check %s[%d] took %0.3f seconds to run, at interval %d (timeout of %d was %s)",
			self.Name, pid, self.duration.Seconds(), self.Every, self.Timeout, timeout_triggered)
	}
	return true
}
开发者ID:qanx,项目名称:bmad,代码行数:75,代码来源:checks.go

示例12: Stop

func (m *Module) Stop() os.Error {
	// 0x02, or SIGINT.
	syscall.Kill(m.MainProcess.Pid, 0x02)
	syscall.Kill(m.SyncProcess.Pid, 0x02)
	// TODO: Check for syscall errors
	modules[m.Name] = nil, false
	return nil
}
开发者ID:Epictetus,项目名称:wfdr,代码行数:8,代码来源:modules.go

示例13: Test_Handle_With2_SIGHUP_ExecutesFnTwice

func Test_Handle_With2_SIGHUP_ExecutesFnTwice(t *testing.T) {
	done := make(chan bool, 1)
	signal.Handle(func() {
		done <- true
	})
	syscall.Kill(syscall.Getpid(), syscall.SIGHUP)
	receiveOnce(t, done)
	syscall.Kill(syscall.Getpid(), syscall.SIGHUP)
	receiveOnce(t, done)
}
开发者ID:daime,项目名称:redis-metrics,代码行数:10,代码来源:signal_test.go

示例14: testCancel

func testCancel(t *testing.T, ignore bool) {
	// Send SIGWINCH. By default this signal should be ignored.
	syscall.Kill(syscall.Getpid(), syscall.SIGWINCH)
	time.Sleep(100 * time.Millisecond)

	// Ask to be notified on c1 when a SIGWINCH is received.
	c1 := make(chan os.Signal, 1)
	Notify(c1, syscall.SIGWINCH)
	defer Stop(c1)

	// Ask to be notified on c2 when a SIGHUP is received.
	c2 := make(chan os.Signal, 1)
	Notify(c2, syscall.SIGHUP)
	defer Stop(c2)

	// Send this process a SIGWINCH and wait for notification on c1.
	syscall.Kill(syscall.Getpid(), syscall.SIGWINCH)
	waitSig(t, c1, syscall.SIGWINCH)

	// Send this process a SIGHUP and wait for notification on c2.
	syscall.Kill(syscall.Getpid(), syscall.SIGHUP)
	waitSig(t, c2, syscall.SIGHUP)

	// Ignore, or reset the signal handlers for, SIGWINCH and SIGHUP.
	if ignore {
		Ignore(syscall.SIGWINCH, syscall.SIGHUP)
	} else {
		Reset(syscall.SIGWINCH, syscall.SIGHUP)
	}

	// Send this process a SIGWINCH. It should be ignored.
	syscall.Kill(syscall.Getpid(), syscall.SIGWINCH)

	// If ignoring, Send this process a SIGHUP. It should be ignored.
	if ignore {
		syscall.Kill(syscall.Getpid(), syscall.SIGHUP)
	}

	select {
	case s := <-c1:
		t.Fatalf("unexpected signal %v", s)
	case <-time.After(100 * time.Millisecond):
		// nothing to read - good
	}

	select {
	case s := <-c2:
		t.Fatalf("unexpected signal %v", s)
	case <-time.After(100 * time.Millisecond):
		// nothing to read - good
	}

	// Reset the signal handlers for all signals.
	Reset()
}
开发者ID:RajibTheKing,项目名称:gcc,代码行数:55,代码来源:signal_test.go

示例15: redirFromWs

func redirFromWs(stdinPipe io.Writer, ws *websocket.Conn, pid int) {
	defer func() {
		if r := recover(); r != nil {
			fmt.Fprintf(os.Stderr, "Error occured: %s\n", r)
			syscall.Kill(pid, syscall.SIGHUP)
			runtime.Goexit()
		}
	}()

	var buf [2048]byte
	for {
		/*
			communication protocol:

			1 byte   cmd

			if cmd = i // input
				8 byte        length (ascii)
				length bytes  the actual input

			if cmd = w // window size changed
				8 byte        cols (ascii)
				8 byte        rows (ascii)
		*/

		readFull(ws, buf[0:1])

		switch buf[0] {
		case 'i':
			length := readInt(ws)
			switch nr, er := io.ReadFull(ws, buf[0:length]); {
			case nr < 0:
				fmt.Fprintf(os.Stderr, "error reading from websocket with code %s\n", er)
				return
			case nr == 0: // EOF
				fmt.Fprintf(os.Stderr, "connection closed, sending SIGHUP to %d\n")
				syscall.Kill(pid, syscall.SIGHUP)
				return
			case nr > 0:
				_, err := stdinPipe.Write(buf[0:nr])
				if err != nil {
					fmt.Fprintf(os.Stderr, "error writing to stdinPipe: %s\n", err.Error())
					return
				}
			}
		case 'w':
			// sadly, we can no longer change window size as easily :(
			// cols, rows := readInt(ws), readInt(ws)
			// setColsRows(winsz, cols, rows)
			// C.goChangeWinsz(C.int(fd), winsz)
		default:
			panic("Unknown command " + string(buf[0]))
		}
	}
}
开发者ID:wyingquan,项目名称:WebTerm,代码行数:55,代码来源:ws.go


注:本文中的syscall.Kill函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。