package main import ( "fmt" "os/exec" ) /* To see the PID, command, and current working directory for all processes, you can run: 1 ps -eo pid,cmd,cwd Explanation * -e: Selects every process on the system. * -o pid,cmd,cwd: Specifies a user-defined format. * pid: Shows the Process ID. * cmd: Shows the command with its arguments. * cwd: Shows the current working directory of the process. Alternative for a Specific Process (Linux) If you already know the PID and just want to find its working directory, there are two even more direct methods on Linux: 1. Using the `pwdx` command: 1 pwdx This will print only the CWD for that specific process. 2. Checking the `/proc` filesystem: The CWD is exposed as a symbolic link. You can read it with ls or readlink: 1 ls -l /proc//cwd This will show you where the cwd link points. */ func main() { fmt.Println("Starting a 'sleep 15' command...") // 1. Create the command. cmd := exec.Command("sleep", "15") // 2. Start the command. This is non-blocking. err := cmd.Start() if err != nil { fmt.Printf("Error starting command: %v\n", err) return } // 3. If Start() succeeded, the PID is now available. // The check for err != nil above is critical to prevent a panic // from a nil pointer dereference on cmd.Process. pid := cmd.Process.Pid fmt.Printf("--> Successfully started process with PID: %d\n", pid) fmt.Println("--> You can verify this with 'ps aux | grep", pid, "'") fmt.Println("Waiting for the process to finish in the background...") // 4. Wait for the command to complete and release its resources. err = cmd.Wait() if err != nil { fmt.Printf("Command finished with error: %v\n", err) } else { fmt.Println("Command finished successfully.") } }