Syscall
- C course
- Expert
- Lesson 2/47
- 5 min
Learn the system call (syscall) concept.
System call (syscall)
A system call (syscall) is how a user program asks the kernel for a service. Each syscall has a number; read, write, open and close are common examples.
In C, <unistd.h> declares these wrappers. When invoked, the CPU traps; the kernel runs the service and returns a value to the user. On error the return is -1 and errno is set. The kernel syscall table maps each number to a function; the table differs per architecture.
Syscall numbers and errno
Each syscall has a number. On Linux x86-64, SYS_read = 0, SYS_write = 1, SYS_open = 2. <sys/syscall.h> defines these constants.
Wrapper functions (read, write) use them indirectly. You can also call syscall(SYS_read, ...) directly, but wrappers are preferred for portability. On error, errno describes the failure; strerror turns it into text. The kernel keeps these numbers stable for ABI compatibility.
Practice Print syscall names
Define void print_syscall(const char *name) with body printf("syscall: %s\n", name);. In main, call it with "read", "write", "open".
Starter code
#include <stdio.h>
// Define print_syscall function
// Call it for read, write, open
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
void print_syscall(const char *name) {
printf("syscall: %s\n", name);
}
int main(void) {
print_syscall("read");
print_syscall("write");
print_syscall("open");
return 0;
}Expected output
syscall: read syscall: write syscall: open
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match syscall wrappers to purpose
| Term | Meaning |
|---|---|
read |
Reads data |
write |
Writes data |
open |
Opens a file |
close |
Closes a descriptor |
2 Which of these is a system call?
- printf
- read Correct answer
- malloc
- fopen
Explanation: read is a direct system call; printf and fopen are libc wrappers.
3 Complete the syscall call
long ret = syscall(____, 1, buf, n);
long ret = syscall(SYS_write, 1, buf, n);
Explanation: SYS_write selects the write system call number.