The process package provides comprehensive functionality for retrieving information about running processes, monitoring resource usage, and managing process lifecycle.
Key Features
Process Discovery List all running processes and create Process instances by PID
Resource Monitoring Monitor CPU, memory, I/O, and other resource usage
Process Information Retrieve detailed process metadata including name, status, command line, and environment
Process Control Send signals, suspend, resume, terminate, and kill processes
Core Type
Process Struct
The main struct representing a system process:
type Process struct {
Pid int32 `json:"pid"`
// ... internal fields ...
}
Most fields are private. Use the Process methods to access process information.
Process Status Constants
const (
Running = "running" // Running or runnable
Blocked = "blocked" // Waiting on I/O
Idle = "idle" // Sleeping for >20 seconds
Lock = "lock" // Waiting to acquire a lock
Sleep = "sleep" // Sleeping (interruptible)
Stop = "stop" // Stopped process
Wait = "wait" // Idle interrupt thread
Zombie = "zombie" // Defunct process
// Solaris-specific
Daemon = "daemon"
Detached = "detached"
System = "system"
Orphan = "orphan"
)
Main Functions
Pids() Get list of all running process IDs
NewProcess() Create a Process instance for a given PID
Processes() Get all running processes as Process instances
PidExists() Check if a process with given PID exists
Process Methods by Category
Cmdline() Get command line string
Status() Get process status
Resource Usage
MemoryInfo() Get memory usage statistics
CPUPercent() Get CPU usage percentage
IOCounters() Get I/O statistics
NumThreads() Get number of threads
Process Relationships
Ppid() - Get parent process ID
Parent() - Get parent Process instance
Children() - Get child processes
User & Security
Username() - Get process owner username
Uids() - Get user IDs
Gids() - Get group IDs
Groups() - Get supplementary group IDs
Process Control
SendSignal(sig) - Send a Unix signal
Suspend() - Send SIGSTOP
Resume() - Send SIGCONT
Terminate() - Send SIGTERM
Kill() - Send SIGKILL
Quick Start
package main
import (
" fmt "
" github.com/shirou/gopsutil/v4/process "
)
func main () {
// List all process IDs
pids , err := process . Pids ()
if err != nil {
panic ( err )
}
fmt . Printf ( "Running processes: %d \n " , len ( pids ))
// Get information about a specific process
p , err := process . NewProcess ( 1234 )
if err != nil {
panic ( err )
}
name , _ := p . Name ()
cpuPercent , _ := p . CPUPercent ()
memInfo , _ := p . MemoryInfo ()
fmt . Printf ( "Process: %s \n " , name )
fmt . Printf ( "CPU: %.2f%% \n " , cpuPercent )
fmt . Printf ( "Memory: %d MB \n " , memInfo . RSS / 1024 / 1024 )
}
Error Handling
Common errors:
ErrorProcessNotRunning - Process does not exist
ErrorNotPermitted - Operation not permitted (insufficient privileges)
package main
import (
" errors "
" fmt "
" github.com/shirou/gopsutil/v4/process "
)
func main () {
p , err := process . NewProcess ( 99999 )
if errors . Is ( err , process . ErrorProcessNotRunning ) {
fmt . Println ( "Process does not exist" )
return
}
// Check if process is still running
running , _ := p . IsRunning ()
if ! running {
fmt . Println ( "Process has terminated" )
}
}
Context Support
All Process methods have context-aware variants with the WithContext suffix:
ctx , cancel := context . WithTimeout ( context . Background (), 5 * time . Second )
defer cancel ()
name , err := p . NameWithContext ( ctx )
cpuPercent , err := p . CPUPercentWithContext ( ctx )
memInfo , err := p . MemoryInfoWithContext ( ctx )
Data Structures
MemoryInfoStat
type MemoryInfoStat struct {
RSS uint64 `json:"rss"` // Resident Set Size
VMS uint64 `json:"vms"` // Virtual Memory Size
HWM uint64 `json:"hwm"` // High Water Mark
Data uint64 `json:"data"` // Data segment size
Stack uint64 `json:"stack"` // Stack size
Locked uint64 `json:"locked"` // Locked memory
Swap uint64 `json:"swap"` // Swapped memory
}
type IOCountersStat struct {
ReadCount uint64 `json:"readCount"`
WriteCount uint64 `json:"writeCount"`
ReadBytes uint64 `json:"readBytes"`
WriteBytes uint64 `json:"writeBytes"`
DiskReadBytes uint64 `json:"diskReadBytes"` // Linux only
DiskWriteBytes uint64 `json:"diskWriteBytes"` // Linux only
}
Retrieving process information can be expensive on systems with many processes. Use context timeouts and consider caching results when appropriate.
For CPU percentage monitoring, call CPUPercent() twice with a delay between calls for accurate measurements, or use Percent() with an interval.
Next Steps
Process Creation Learn about creating Process instances
Process Info Get detailed process information
Memory Monitoring Monitor memory usage
CPU Monitoring Monitor CPU usage