Middle
What does the fork() system call do?
sobes.tech AI
Answer from AI
The fork() system call in Unix-based operating systems creates a new process that is a copy of the calling process (the parent). The new process is called the child. After calling fork(), you have two processes that continue execution from the point of the call.
Features:
- The child process receives a copy of the parent's address space.
- The return value of
fork()allows processes to be distinguished:- In the parent process, it returns the PID of the child process.
- In the child process, it returns 0.
- On error, it returns -1.
Example in Go (using syscall, as Go does not have a direct fork):
package main
import (
"fmt"
"syscall"
)
func main() {
pid, _, err := syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0)
if err != 0 {
fmt.Println("Fork failed")
return
}
if pid == 0 {
fmt.Println("This is the child process")
} else {
fmt.Printf("This is the parent process, child PID: %d\n", pid)
}
}
In Go, exec.Command and goroutines are more commonly used instead of fork().