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


Golang os.Getpid函数代码示例

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


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

示例1: 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

示例2: main

func main() {

	http.HandleFunc("/sleep/", func(w http.ResponseWriter, r *http.Request) {
		duration, err := time.ParseDuration(r.FormValue("duration"))
		if err != nil {
			http.Error(w, err.Error(), 400)
			return
		}

		time.Sleep(duration)

		fmt.Fprintf(
			w,
			"started at %s slept for %d nanoseconds from pid %d.\n",
			time.Now(),
			duration.Nanoseconds(),
			os.Getpid(),
		)
	})

	log.Println(fmt.Sprintf("Serving :8080 with pid %d.", os.Getpid()))

	gracehttp.ListenAndServe(":8080", nil)

	log.Println("Server stoped.")
}
开发者ID:Andals,项目名称:gpm,代码行数:26,代码来源:main.go

示例3: New

func New(id circuit.WorkerID, bindAddr string, host string) *Transport {

	// Bind
	var l *net.TCPListener
	if strings.Index(bindAddr, ":") < 0 {
		bindAddr = bindAddr + ":0"
	}
	l_, err := net.Listen("tcp", bindAddr)
	if err != nil {
		panic(err)
	}

	// Build transport structure
	l = l_.(*net.TCPListener)
	t := &Transport{
		listener:   l,
		addrtabl:   makeAddrTabl(),
		pipelining: DefaultPipelining,
		remote:     make(map[circuit.WorkerID]*link),
		ach:        make(chan *conn),
	}

	// Resolve self address
	laddr := l.Addr().(*net.TCPAddr)
	t.self, err = NewAddr(id, os.Getpid(), fmt.Sprintf("%s:%d", host, laddr.Port))
	if err != nil {
		panic(err)
	}

	// This LocalAddr might be useless for connect purposes (e.g. 0.0.0.0). Consider self instead.
	t.bind = t.addrtabl.Normalize(&Addr{ID: id, PID: os.Getpid(), Addr: laddr})

	go t.loop()
	return t
}
开发者ID:rrudduck,项目名称:golang-stuff,代码行数:35,代码来源:transport.go

示例4: TestNewStatus

func TestNewStatus(t *testing.T) {
	now := time.Now()
	mem := runtime.MemStats{Alloc: 0}
	status := NewStatus("v1", now, &mem)

	if status == nil {
		t.Fatal("status is nil")
	}
	if status.Code != "OK" {
		t.Errorf("status is %s, expected %s", status.Code, "OK")
	}
	if status.Version != "v1" {
		t.Errorf("version is %s, expected %s", status.Version, "v1")
	}
	if host := fmt.Sprintf("%s_%s", runtime.GOOS, runtime.GOARCH); status.Host != host {
		t.Errorf("host is %s, expected %s", status.Host, host)
	}
	if status.PID != os.Getpid() {
		t.Errorf("PID is %d, expected %d", status.PID, os.Getpid())
	}
	if status.StartedAt != now {
		t.Errorf("version is %v expected %v", status.StartedAt, now)
	}
	if status.NumberGoroutines != runtime.NumGoroutine() {
		t.Errorf("number of goroutines is %v expected %v", status.StartedAt, now)
	}
	if status.MemoryAlloc != "0B" {
		t.Errorf("memory allocated is %v, expected to be %v", status.MemoryAlloc, "0.00MB")
	}
}
开发者ID:fern4lvarez,项目名称:piladb,代码行数:30,代码来源:status_test.go

示例5: sendPacket

func sendPacket(conn net.PacketConn, destination *net.IPAddr, payload []byte, seq int) {
	packet := make([]byte, len(payload)+8)
	packet[0] = 8
	packet[1] = 0
	packet[4] = uint8(os.Getpid() >> 8)
	packet[5] = uint8(os.Getpid() & 0xff)
	packet[6] = uint8(seq >> 8)
	packet[7] = uint8(seq & 0xff)
	copy(packet[8:], payload)

	cklen := len(packet)
	cksum := uint32(0)
	for i := 0; i < cklen-1; i += 2 {
		cksum += uint32(packet[i+1])<<8 | uint32(packet[i])
	}
	if cklen&1 == 1 {
		cksum += uint32(packet[cklen-1])
	}
	cksum = (cksum >> 16) + (cksum & 0xffff)
	cksum = cksum + (cksum >> 16)

	packet[2] ^= uint8(^cksum & 0xff)
	packet[3] ^= uint8(^cksum >> 8)

	_, err := conn.WriteTo(packet, destination)
	if err != nil {
		panic(err)
	}
}
开发者ID:ragnar-johannsson,项目名称:icmp-echo-file,代码行数:29,代码来源:icmp-echo-file.go

示例6: processMetrics

func processMetrics() {
	var (
		g    = metrics.NewGauge()
		fg   = metrics.NewGauge()
		memg = metrics.NewGauge()
	)
	metrics.DefaultRegistry.Register("goroutines", g)
	metrics.DefaultRegistry.Register("fds", fg)
	metrics.DefaultRegistry.Register("memory-used", memg)
	collect := func() {
		// update number of goroutines
		g.Update(int64(runtime.NumGoroutine()))
		// collect the number of open fds
		fds, err := osutils.GetOpenFds(os.Getpid())
		if err != nil {
			logrus.WithField("error", err).Error("containerd: get open fd count")
		}
		fg.Update(int64(fds))
		// get the memory used
		m := sigar.ProcMem{}
		if err := m.Get(os.Getpid()); err != nil {
			logrus.WithField("error", err).Error("containerd: get pid memory information")
		}
		memg.Update(int64(m.Size))
	}
	go func() {
		collect()
		for range time.Tick(30 * time.Second) {
			collect()
		}
	}()
}
开发者ID:Altiscale,项目名称:containerd,代码行数:32,代码来源:main.go

示例7: wait

// Wait for 10 consecutive responses from our own pid.
//
// This prevents flaky tests that arise from the fact that we have the
// perfectly acceptable (read: not a bug) condition where both the new and the
// old servers are accepting requests. In fact the amount of time both are
// accepting at the same time and the number of requests that flip flop between
// them is unbounded and in the hands of the various kernels our code tends to
// run on.
//
// In order to combat this, we wait for 10 successful responses from our own
// pid. This is a somewhat reliable way to ensure the old server isn't
// serving anymore.
func wait(wg *sync.WaitGroup, url string) {
	var success int
	defer wg.Done()
	for {
		res, err := http.Get(url)
		if err == nil {
			// ensure it isn't a response from a previous instance
			defer res.Body.Close()
			var r response
			if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
				log.Fatalf("Error decoding json: %s", err)
			}
			if r.Pid == os.Getpid() {
				success++
				if success == 10 {
					return
				}
				continue
			}
		} else {
			success = 0
			// we expect connection refused
			if !strings.HasSuffix(err.Error(), "connection refused") {
				e2 := json.NewEncoder(os.Stderr).Encode(&response{
					Error: err.Error(),
					Pid:   os.Getpid(),
				})
				if e2 != nil {
					log.Fatalf("Error writing error json: %s", e2)
				}
			}
		}
	}
}
开发者ID:train860,项目名称:picfit,代码行数:46,代码来源:testserver.go

示例8: main

func main() {

	sigChan := make(chan os.Signal)
	log.Println("pid==", os.Getpid())
	pid := os.Getpid()
	process, err := os.FindProcess(pid)
	if err != nil {
		log.Println(err)
	}

	signal.Notify(sigChan, syscall.SIGHUP, syscall.SIGINT)

	for {
		select {
		case sig := <-sigChan:
			switch sig {
			case syscall.SIGHUP:
				log.Println("SIGNAL SIGHUP")
			case syscall.SIGINT:
				log.Println("SIGNAL SIGINT")
				process.Kill()
			}
		}
	}
}
开发者ID:wanghe4096,项目名称:golang_demo,代码行数:25,代码来源:go-notify.go

示例9: TestPidFile

func TestPidFile(t *testing.T) {
	opts := DefaultTestOptions

	tmpDir, err := ioutil.TempDir("", "_gnatsd")
	if err != nil {
		t.Fatal("Could not create tmp dir")
	}
	defer os.RemoveAll(tmpDir)

	file, err := ioutil.TempFile(tmpDir, "gnatsd:pid_")
	file.Close()
	opts.PidFile = file.Name()

	s := RunServer(&opts)
	s.Shutdown()

	buf, err := ioutil.ReadFile(opts.PidFile)
	if err != nil {
		t.Fatalf("Could not read pid_file: %v", err)
	}
	if len(buf) <= 0 {
		t.Fatal("Expected a non-zero length pid_file")
	}

	pid := 0
	fmt.Sscanf(string(buf), "%d", &pid)
	if pid != os.Getpid() {
		t.Fatalf("Expected pid to be %d, got %d\n", os.Getpid(), pid)
	}
}
开发者ID:JimmyMa,项目名称:gnatsd,代码行数:30,代码来源:pid_test.go

示例10: TestIsPortBound

func TestIsPortBound(t *testing.T) {
	port := "8080"
	go func() {
		err := http.ListenAndServe(fmt.Sprintf(":%s", port), nil)
		if err != nil {
			t.Fatal(err)
		}
	}()

	maxTry := 10
	for i := 0; i < maxTry; i++ {
		pid, err := IsPortBound(port, []int{os.Getpid()})
		if err != nil {
			t.Fatal(err)
		}
		if pid == -1 {
			continue //port not bound yet
		}
		//port bound
		if pid != os.Getpid() {
			t.Fatal("expect port to be bound by %d, got %d", os.Getpid(), pid)
		} else {
			return // ok
		}
	}
	t.Fatal("port never bound :(")
}
开发者ID:robinmonjo,项目名称:dock,代码行数:27,代码来源:port_test.go

示例11: TestInitd

func TestInitd(t *testing.T) {
	t.Parallel()

	l, err := detectInitd("./")
	assert.Nil(t, err)
	assert.NotNil(t, l)

	assert.Equal(t, "init.d", l.Name())

	// service does not exist
	st, err := l.LookupService("apache2")
	assert.NotNil(t, err)
	assert.Equal(t, err.(*ServiceError).Err.Error(), "No such service")
	assert.Nil(t, st)

	// service exists but pidfile doesn't
	st, err = l.LookupService("mysql")
	assert.Nil(t, err)
	assert.NotNil(t, st)
	assert.Equal(t, 0, st.Pid)
	assert.Equal(t, Down, st.Status)

	// Need to be able to kill -0 the PID and our own process
	// is the only one we can be sure of.
	i := l.(*Initd)
	i.pidParser = func(_ []byte) (int, error) { return os.Getpid(), nil }

	// service exists and pidfile exists
	st, err = l.LookupService("redis")
	assert.Nil(t, err)
	assert.Equal(t, os.Getpid(), st.Pid)
	assert.Equal(t, Up, st.Status)
}
开发者ID:rquelle,项目名称:inspeqtor,代码行数:33,代码来源:initd_test.go

示例12: prog

//prog(state) runs in a child process
func prog(state overseer.State) {
	// pp.Println(state)
	log.Println("Prog: start PID: ", os.Getpid(), os.Getppid())
	log.Println("Building date: ", buildDate)
	log.Printf("app (%s) listening at %s...", state.ID, state.Listener.Addr())
	http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Println("Get handle from ", r.RemoteAddr, r.RequestURI)
		log.Println("PID=", os.Getpid())
		fmt.Fprintln(w, "<h1>Test overseer server</h1>")
		fmt.Fprintln(w, `<a href="https://github.com/jpillora/overseer">Overseer home page</a>`)
		fmt.Fprintf(w, "<p>Build date: %s</p>", buildDate)
		counter++
		fmt.Fprintf(w, "<p>My app (%s) says hello %d times</p>\n", state.ID, counter)
		fmt.Fprintf(w, "<p>PID=%d, PPID=%d</p>\n", os.Getpid(), os.Getppid())
		fmt.Fprintf(w, "<p>Application: %s</p>\n", os.Args[0])

		fmt.Fprintf(w, "<hr/><p>Args: %v</p>", os.Args[1:])
		fmt.Fprintln(w, "<hr/><ul>\n")
		for _, env := range os.Environ() {
			fmt.Fprintf(w, "<li>Env: %v</li>\n", env)
		}
		fmt.Fprintln(w, "</ul>\n")

	}))
	http.Serve(state.Listener, nil)
	log.Println("Stop server ", os.Getpid())
}
开发者ID:plumbum,项目名称:go-samples,代码行数:28,代码来源:main.go

示例13: main

func main() {
	lf, err := os.OpenFile(lfn, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
	if err == nil {
		// good
		// 10 digit pid seems to be a standard for lock files
		fmt.Fprintf(lf, "%10d", os.Getpid())
		lf.Close()
		defer os.Remove(lfn)
	} else {
		// problem
		fmt.Println(err)
		// dig deeper
		lf, err = os.Open(lfn)
		if err != nil {
			return
		}
		defer lf.Close()
		fmt.Println("inspecting lock file...")
		b10 := make([]byte, 10)
		_, err = lf.Read(b10)
		if err != nil {
			fmt.Println(err)
			return
		}
		pid, err := strconv.Atoi(strings.TrimSpace(string(b10)))
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println("lock file created by pid", pid)
		return
	}
	fmt.Println(os.Getpid(), "running...")
	time.Sleep(1e10)
}
开发者ID:travis1230,项目名称:RosettaCodeData,代码行数:35,代码来源:determine-if-only-one-instance-is-running.go

示例14: TestIngest

func TestIngest(t *testing.T) {
	type obj map[string]interface{}

	if testing.Verbose() {
		logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"elasticsearch"})
	}

	index := fmt.Sprintf("beats-test-ingest-%d", os.Getpid())
	pipeline := fmt.Sprintf("beats-test-pipeline-%d", os.Getpid())

	pipelineBody := obj{
		"description": "Test pipeline",
		"processors": []obj{
			{
				"lowercase": obj{
					"field": "testfield",
				},
			},
		},
	}

	client := GetTestingElasticsearch()
	_, _, err := client.DeletePipeline(pipeline, nil)

	_, resp, err := client.CreatePipeline(pipeline, nil, pipelineBody)
	if err != nil {
		t.Fatal(err)
	}
	if !resp.Acknowledged {
		t.Fatalf("Test pipeline %v not created", pipeline)
	}

	params := map[string]string{"refresh": "true"}
	_, resp, err = client.Ingest(index, "test", pipeline, "1", params, obj{
		"testfield": "TEST",
	})
	if err != nil {
		t.Fatalf("Ingest() returns error: %s", err)
	}
	if !resp.Created {
		t.Errorf("Ingest() fails: %s", resp)
	}

	// get _source field from indexed document
	_, docBody, err := client.apiCall("GET", index, "test", "1/_source", "", nil, nil)
	if err != nil {
		t.Fatal(err)
	}

	doc := struct {
		Field string `json:"testfield"`
	}{}
	err = json.Unmarshal(docBody, &doc)
	if err != nil {
		t.Fatal(err)
	}

	assert.Equal(t, "test", doc.Field)
}
开发者ID:cyrilleverrier,项目名称:beats,代码行数:59,代码来源:api_integration_test.go

示例15: Println

func (v *loggerPlus) Println(ctx Context, a ...interface{}) {
	if ctx == nil {
		a = append([]interface{}{fmt.Sprintf("[%v]", os.Getpid())}, a...)
	} else {
		a = append([]interface{}{fmt.Sprintf("[%v][%v]", os.Getpid(), ctx.Cid())}, a...)
	}
	v.logger.Println(a...)
}
开发者ID:ossrs,项目名称:go-oryx-lib,代码行数:8,代码来源:logger.go


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