How does a system call work

Rocoder picture Rocoder · Jun 4, 2014 · Viewed 19.5k times · Source

How does system calls work ?
What are the operations happen during system call?
There are various system call like open , read, write, socket etc. I would like to know how do they work in general ?

Answer

haccks picture haccks · Jun 4, 2014

In short, here's how a system call works:

  • First, the user application program sets up the arguments for the system call.
  • After the arguments are all set up, the program executes the "system call" instruction.
  • This instruction causes an exception: an event that causes the processor to jump to a new address and start executing the code there.

  • The instructions at the new address save your user program's state, figure out what system call you want, call the function in the kernel that implements that system call, restores your user program state, and returns control back to the user program.

A visual explanation of a user application invoking the open() system call:

enter image description here

It should be noted that the system call interface (it serves as the link to system calls made available by the operating system) invokes intended system call in OS kernel and returns status of the system call and any return values. The caller need know nothing about how the system call is implemented or what it does during execution.
Another example: A C program invoking printf() library call, which calls write() system call

enter image description here

For more detailed explanation read section 1.5.1 in CH-1 and Section 2.3 in CH-2 from Operating System Concepts.