Junior — Middle
Can you explain what system calls are and how they work in an operating system?
sobes.tech AI
Answer from AI
System calls are an interface between user programs and the kernel of the operating system. They allow programs to request the OS to perform operations that require privileges, such as working with files, networks, processes, or memory.
When a program invokes a system call, it transitions from user mode to kernel mode (privileged mode). The OS performs the necessary operation and returns the result to the program. This ensures security and stability, as direct access to hardware is restricted.
An example of a system call in Go for reading a file:
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Open("example.txt") // invokes the open system call
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()
buf := make([]byte, 100)
n, err := file.Read(buf) // invokes the read system call
if err != nil {
fmt.Println("Error reading file:", err)
return
}
fmt.Println(string(buf[:n]))
}
Here, the functions os.Open and file.Read use system calls to interact with the file system.