top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How sbrk and mmap system calls are functionally different ?

+1 vote
787 views
How sbrk and mmap system calls are functionally different ?
posted Jun 22, 2014 by Ganesh

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

I know about only sbrk system call and would like to share information about sbrk.

When a process needs more space or memory, it asks to OS to grant more memory. However, it is up to kernal whether it gives or not. There is a maximum limit of space/memory that a process can have.

Function prototype:
void * sbrk(intptr_t increment);

Program running in user space call sbrk with request size as parameter. if it successful then return valid pointer else null.
Note: If sbrk calls with parameter 0 then it returns current address of end of data segment.

answer Jun 22, 2014 by Harshita
When you want to read/write to/from files so that the information is shared between processes. In the normal operation two processes both open the same file and both read and write from it, thus sharing the information. The problem is, sometimes it's a pain to do all those fseek()s and stuff to get around.

It be lot easier if we can just map a section of the file to memory, and get a pointer to it? Then we can simply use pointer arithmetic to get (and set) data in the file. And here mmap is used.

Syntax:
void *mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t off);
(check the Linux man page for more detail on each parameter, the only point I want to mention here us that the len and off parameter should be multiple of virtual page size)

Example Usage:
fd = open("MyFile", O_RDONLY);
pagesize = getpagesize();
data = mmap((caddr_t)0, pagesize, PROT_READ, MAP_SHARED, fd, pagesize);
...