I would like to know what is the difference between a Library call and a System call in Linux. Any pointers for a good understanding of the concepts behind both will be greatly appreciated.
There's not really such a thing as a "library call". You can call a function that's linked to a shared library. And that just means that the library path is looked up at runtime to determine the location of the function to call.
System calls are low level kernel calls handled by the kernel.
If you type
man man in your shell, you will see the list of the manual sections
2 System calls (functions provided by the kernel)
3 Library calls (functions within program libraries)
For instance, you will find
chmod in the section 2 of the manual when typing
man chmod. And
fprintf in the section 3.
System calls are handled directly by the kernel.
Library calls are handled by a dynamic (or statically linked) library. The program making the library call must first import that library, before the call will work. The library calls themselves may use system calls.
Sometimes libraries are provided as "front-ends" to system calls, to provide extra functionality or ease of use not provided by the kernel.
System calls are functions that the operating system provides for applications to use. Whereas functions like the ones in math.h, string.h, etc are those that doesn't have anything to do with interfacing with the operating system.
Basically there are two modes of linux kernel viz.
- User mode,
- Kernel mode.
Any linux kernel switches itself back and forth between these two modes. Generally, Library calls get executed in User mode and System calls get executed in Kernel mode. In operating system terms, Kernel mode is Atomic in nature and its in Supervisory mode. Almost all Library calls need help from the kernel to perform its tasks. Each library call in turn calls underlying system call. Let us make idea more clearer using following example
- fopen() : is a Library call,
- open() : is a System call.
Whenever in c program, you use fopen() from header file. Programming environment calls system call open() from kernel and perform its file opening task. Again after executing, control flow return to user mode.
To illustrate this perform following tasks
man man: here you will find manual section from 1-8 each has specific purpose.
man fopen: you will see respose as
FOPEN(3), here 3 indicate manual section 3 of man pages which is c-library calls section.
man open: you will see respose as
OPEN(2), here 2 indicate manual section 2 of man pages which is system calls section.
Hope you understood the concept.
Just adding to the differences mentioned here in other answers.
Since a library call is simply a function call, no switch from user space to kernel space occurs. On the other hand, a system call results in a switch from user space to kernel space because the system call operates in kernel mode.