Question

In Linux, when you can choose between a system call or a function call to do a task, which option is the better one due to a better performance?

Was it helpful?

Solution

We should note that in most of the cases we do not directly use system call. We use the interface provided by glibc.

http://www.kernel.org/doc/man-pages/online/pages/man2/syscalls.2.html

http://www.gnu.org/software/libc/manual/html_node/System-Calls.html

Now in cases like File Mangement/IPC/ process management etc which are the core resource management activities of the Operating System the only option is system call and not library functions.

In these cases, typically we use Library function which works as a wrapper over a system call. That is say for reading a file, we have many library functions like

fgetc/fgets/fscanf/fread -  all should invoke read system call.

So shall we use read system call? or the other library functions? This should depend on the particular application.If we are using read, then we again need to change the code to run this, on some other operating system where read is not available.

We are losing some flexibilty. It may be useful when we are sure of the platform and we can do some optimisations by using read only or may be the application must use only file descriptors and not file pointer etc.

Now in cases where we need to consider only say user level operations and invoke 
no    service from operating system , like say copying a string.(strcpy).
In this case definitely we shall not use any system call unnecessarily, if at
all something is  there, since it should be an extra overhead due to operating 
system intervention, which is not needed in this case.

So I feel choosing between a system call and a library function only occurs for cases where we have a library function built on top of a system call.

(like adding to examples above we can have say malloc which calls system call brk).

Here the choice will depend on the particular type of software, the platform on which it should run, the precise non functional requirements like speed (Though you cannot say with certainty that your code will run faster if you are using brk instead of malloc), portability etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top