kms
kms

Reputation: 163

Get Parent process id from child process id using Golang

I want to get parent process id (ppid) from specific child process id (pid) using Golang for Linux os

I have this code which gives ppid and pid of the current process but I want to retrieve ppid of the child process which I specify and not the current process.

package main

 import (
         "fmt"
         "os"
 )

 func main() {

         pid := os.Getpid()

         parentpid := os.Getppid()

         fmt.Printf("The parent process id of %v is %v\n", pid, parentpid)

 }

Is there a way to pass pid like this os.Getppid(pid) or any other method to retrieve ppid of specified pid in Golang?

Upvotes: 6

Views: 6208

Answers (2)

Bhautik Chudasama
Bhautik Chudasama

Reputation: 712

You can use os.FindProcess(os.Getppid()). Learn more at https://pkg.go.dev/os#FindProcess

Upvotes: 3

bithavoc
bithavoc

Reputation: 1539

I don't think the go standard library allows you to do this, however, third-party packages such as mitchellh/go-ps provide more information.

Example:

import ps "github.com/mitchellh/go-ps"
...

list, err := ps.Processes()
if err != nil {
  panic(err)
}
for _, p := range list {
  log.Printf("Process %s with PID %d and PPID %d", p.Executable(), p.Pid(), p.PPid())
}

Output:

2019/06/12 09:13:04 Process com.apple.photom with PID 68663 and PPID 1
2019/06/12 09:13:04 Process CompileDaemon with PID 49896 and PPID 49895

You can also use ps.FindProcess(<pid>) to find a specific process and inspect its PPid

Upvotes: 4

Related Questions