exec function comes in.
What is exec?The
exec system call replaces the current process image with a new process image. This is different from spawning, where both processes continue to run.How Exec Works
When you exec a process:- The current Go process ends
- The new process takes its place
- The new process inherits the same process ID
- If successful, code after the exec call never executes
Basic Example
Here’s how to exec thels command:
Step-by-Step Breakdown
Find the binary
Use
exec.LookPath to get the absolute path to the executable. Go requires absolute paths for exec.Prepare arguments
Arguments must be provided as a slice. The first argument should be the program name.
Set environment
Provide environment variables for the new process. Usually you’ll pass your current environment.
Key Requirements
Absolute Path Required
Absolute Path Required
Go requires an absolute path to the binary. Use
exec.LookPath to find executables in your system’s PATH.Arguments as Slice
Arguments as Slice
Unlike some shell commands, arguments must be provided as a string slice, not a single string.
Program Name Convention
Program Name Convention
By convention, the first element in the arguments slice should be the name of the program being executed.
Example Output
When you run this program, it gets replaced byls:
ls, not from your Go program.
No Fork in Go
When to Use Exec vs Spawn
Use Exec When
- You want to replace your Go program entirely
- Building a wrapper or launcher program
- Implementing a process supervisor that becomes the supervised process
Use Spawn When
- You need to run a command and continue your Go program
- You want to capture the command’s output
- You need to run multiple commands
Related Topics
Spawning Processes
Create new processes alongside your Go program
Environment Variables
Work with environment variables in Go