UNIX Process. Process is any program which is executed by computer’s operation system. Kernel is Operation System, that interacts with hardware and provides services like Memory Management, CPU scheduling, Filesystem, I/O Device access, etc. System Call - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
is any program which is executed by computer’s operation system.
Kernel is Operation System, that interacts with hardware and provides services like Memory Management, CPU scheduling, Filesystem, I/O Device access, etc.
System Callis direct entry point, provided by Kernel, through which active Process can obtain the service
Process Representation in Memory
Text
Initialized Read-Only Data
Initialized Read-Write Data
Uninitialized Data
Heap
Stack Kernel Data
read from program file when program is executed
User Context Kernel Context
Text
Actual machine instructions to be executed by hardware
Data
Program’s data, declared during program start
Heap
Data space, dynamically allocated by the Process
Stack
Dynamically allocated Stack Frames, containing return address linkage and data elements for each function call
•The fork() system call creates the copy of process that is executing.• It is an only way in which a new process is created in UNIX.• Returns: child PID >0 - for Parent process,
0 - for Child process,
-1 - in case of error (errno indicates the error).• Fork reasons:
-Make a copy of itself to do another task simultaneously-Execute another program (See exec system call)
pid_t childPID; /* typedef int pid_t */…childPID = fork();
if (childPID < 0){ perror(“fork failed”); exit(1);}else if (childPID > 0) /* This is Parent */{ /* Parent processing */ … exit(0);}else /* childPID == 0 */ /* This is Child */{ /* Child processing */ … exit(0);}
parentfork
Child Process has Shared Text and Copied Data.
It differs from Parent Process by following attributes:• PID (new)• Parent PID (= PID of Parent Process)• Own copies of Parent file descriptors• Time left until alarm signal reset to 0
PPID of Child is set to 1,INIT process will call WAIT.
PPID of Child is set to 1Terminated, WAIT was not called
Child becomes Zombie, Child remains in Process Table until WAIT will be called
------------Running, WAIT is not called yet
Parent accepts Child’s PID and termination status immediately.Child is deleted from Process Table.
Parent blocks waiting for Child Termination
Running, calls WAIT
TerminatedRunningCHILDPARENT
Wait System Call
Exit System Call
#include <stdlib.h>void exit (int status);
• Terminates process execution.• Exit status is passed to the Kernel and then available to the Parent Process (with wait() call)• Only low-order 1 byte used to specify the exit status (0 - success, 1-255 – error)
#include <sys/wait.h>pid_t wait (int *p_status);
• Waits for one of the children process to finish.• Returns: child PID > 0 - PID of child process terminated with exit system call or with signal, -1 - if there aren’t child processes or if wait interrupted with signal (errno=EINTR).• If p_status is not NULL, the 2 low-order bytes will be filled with process status information
Child process terminated with exit(), but yet not wait()-ed by Parent process, becomes Zombie or Defunct.Its main resources are released by Kernel, but it still present in Process Table until Parent will read its status.If a parent process terminated without wait()-ing for its children, the parent PID of each child process is set to 1.
Waitpid System Call #include <sys/wait.h>pid_t waitpid (pid_t pid, int *p_status, int options);
• Waits for one of the children process to finish (performs functionality of wait with additional options).• The pid argument may be: > 0 - PID of particular process = 0 - sender’s process group =-1 - all sender’s processes <-1 - process group ID = abs(pid)
• The options argument may be:
WNOHANG - check status of terminated processes in non-blocking mode WUNTRACED - report also the status of stopped child processes• If p_status is not NULL, the 2 low-order bytes will be filled with Process Status information.• Returns: child PID > 0 of child process terminated with exit system call or with signal,
-1 - if there aren’t child processes,-1 (errno=EINTR) - if wait interrupted with signal,
-1 (errno=ECHILD) - if argument pid is invalid,-1 (errno=EINVAL) - if argument options is invalid, 0 - if WNOHANG option is specified and child process(es) still running
WIFEXITED(status), WEXITSTATUS(status),
WIFSIGNALED(status), WTERMSIG(status),
WIFSTOPPED(status), WSTOPSIG(status)
Process Status Evaluation
Process Status High Order byte
Low Order byte
Terminated due to exit() Exit Status 0
Terminated by signal 0 Signal Number
Stopped( reported only by waitpid() )
Signal Number WSTOPFLG
To evaluate process status the following MACROs are used: int * p_status
File System Management (Input/Output) System Calls
createerrorO_...|O_CREAT|O_EXCL (mode used)
createopenO_...|O_CREAT (mode used)
erroropenO_...
No
File exists
O_CREAT and O_EXCLFlags Combination: Yes
With each File, open by specific Process, the Kernel associates the unique integer value in the scope of this process.
This integer key is named File Descriptor. It is used as file identifier for all subsequent read and write operations.
By default, the File Descriptors 0, 1 and 2 are associated with Standard Input, Output and Error correspondently.
#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>int open (const char *path, int oflag, …/*mode_t mode*/);
• Opens file specified by path-name• Argument oflag specifies one of following open modes:
O_RDONLY (=0) read-only, O_WRONLY (=1) write-only, O_RDWR (=2) read & write• The following bit flag values could be added with bitwise-OR operator (see also man):
O_APPEND - all writes append data to the end of file
O_TRUNC - if open for write, the file is truncated to 0 bytes length
O_CREAT - file will be created if it does not exist yet
O_EXCL - used with O_CREAT for exclusive creation• Argument mode is used with O_CREAT flag and specifies
the permissions of creating file as octal constant.• Returns File Descriptor (>=0) in case of success.
Returns -1 in case of error, errno value specifies the error (see man).
• Deallocates File Descriptor specified by fd.
This File Descriptor could be reused by subsequent open() calls.• Returns 0 on success. Returns -1 in case of error, errno value specifies the error.
#include <unistd.h>int close (int fd);
Process
0 1 2 3 N…4
std
ou
t
std
in
std
err
File
A
Example. Open File
fd=open(“FileA”, O_RDWR);/* As result, fd equal 3 */
• Reads no more than nbyte-s from file associated with descriptor fd into buffer buf.• Returns non-negative number of read bytes. Returns -1 in case of error, errno value specifies the error.
• Writes nbyte-s from buffer buf to the file associated with descriptor fd .• Returns non-negative number of written bytes. Returns -1 in case of error, errno value specifies the error.
• Sets the file pointer associated with the open file descriptor fd as follows: - if whence == SEEK_SET, the pointer is set to offset bytes from file beginning. - if whence == SEEK_CUR, the pointer is set to its current location plus offset. - if whence == SEEK_END, the pointer is set to the size of the file plus offset.• Returns the resulting offset calculated from file beginning. Returns -1 in case of error, errno specifies the error.
#include <sys/types.h>#include <unistd.h>off_t lseek (int fd, off_t offset, int whence);
The Standard C Library provides the data type FILE representing Buffered Stream Object and set of functions
• Associates Buffered Stream with already open File Descriptor.• Argument mode could have the same values (“r”, “w”, “a”, “r+”, “w+”, “a+”) as for fopen() function.• Returns FILE* pointer to Buffered Stream object or NULL in case of error.
FILE *popen(const char *command, const char *mode); int pclose(FILE *stream);
• Function popen() creates a pipe between the calling program and the command to be executed.• The command argument consists of a shell command line, that is invoked as follows:
• The mode argument is either “r” for reading or “w” for writing.• Depending on mode, calling program could read from STDIN or write to STDOUT of the command.• Function pclose() closes a pipe, waits for the associated process and returns its termination status.
Name Value Default Event===========================================================SIGHUP 1 Exit Hangup on controlling terminal SIGINT 2 Exit Interrupt (Ctrl-C)SIGQUIT 3 Core Quit – interactive terminationSIGILL 4 Core Illegal InstructionSIGTRAP 5 Core Trace or Breakpoint TrapSIGABRT 6 Core Abort – abnormal terminationSIGEMT 7 Core Emulation TrapSIGFPE 8 Core Arithmetic ExceptionSIGKILL 9 Exit Killed (can’t be changed)SIGBUS 10 Core Bus Error (undefined memory access)SIGSEGV 11 Core Segmentation Fault (invalid memory reference)SIGSYS 12 Core Bad System CallSIGPIPE 13 Exit Broken PipeSIGALRM 14 Exit Alarm Clock (timeout signal)SIGTERM 15 Exit TerminatedSIGUSR1 16 Exit User Signal 1SIGUSR2 17 Exit User Signal 2SIGCHLD 18 Ignore Child Status ChangedSIGPWR 19 Ignore Power Fail or RestartSIGWINCH 20 Ignore Window Size ChangeSIGURG 21 Ignore Urgent Socket ConditionSIGPOLL 22 Exit Pollable Event SIGSTOP 23 Stop Stopped (can’t be changed)SIGTSTP 24 Stop Stopped (user) (Ctrl-Z)SIGCONT 25 Ignore Continued (command fg)SIGTTIN 26 Stop Stopped (tty input) SIGTTOU 27 Stop Stopped (tty output)SIGVTALRM 28 Exit Virtual Timer ExpiredSIGPROF 29 Exit Profiling Timer ExpiredSIGXCPU 30 Core CPU time limit exceeded SIGXFSZ 31 Core File size limit exceeded
Signal is software interrupt used as notification to process about some event.
Process accepts a signals:• sent by Kernel• sent by another process
• Sends a signal to the process(es) specified by each pid operand.• The pid argument may be: >0 - PID of particular process =0 - sender’s process group -1 - all sender’s processes <-1 - process group ID = abs(pid)• With -l parameter writes all supported signal names
Sending and Handling the Signal#include <sys/types.h>#include <signal.h>
int kill(pid_t pid, int sig);
• System call kill() sends a signal to a process or a group of processes.• The sender and receiver must have the same effective user ID or sender must be superuser.• Sending sig = 0 used to check process existence.• The pid argument could have the following values:
>0 - PID of particular process=0 - sender’s process group-1 - all sender’s processes<-1 - process group ID = abs(pid)
• The kill() call returns 0 in case of success. In case of failure -1 is returned, errno indicates the error.
• System call signal() modifies signal disposition. • The sig specifies any signal, excepting SIGKILL and SIGSTOP. • The sig_handler argument specifies the signal's disposition, which may be:
- SIG_DFL - to provide default signal handling - SIG_IGN - to ignore the signal - user-defined handler name - to provide specific signal handling with specific handler
• The signal() call returns the previous handler (disposition) of the signal.
#include <unistd.h>
int pause(void);
•System call pause() suspends the calling process until it receives a signal. • If process is not terminated by signal, returns value -1 and sets errno=EINTR
int raise(int sig);
• Sends the signal sig to executing program. • Is equivalent to kill(getpid(), sig)
ExamplesExample 1. Suspend / Resume application output with SIGINT signal (sent with Ctrl-C).
#include <signal.h>int flag=0;
/*--- Signal SIGINT handler--- */void sigreact (int sig){ /* OS-depended re-subscription*/ /* signal(SIGINT,sigreact); */ flag = ! flag;}…/*--- Prints application data ---*/void printInfo(…){ … /* subscribe to signal */ signal (SIGINT, sigreact); while(…/*has more data */)
{ while(flag) { /* wait for signal */ pause ( ); }
printf(…/*print the data*/);
}
/* unsubscribe from signal */ signal (SIGINT, SIG_DFL); … }
Example 2.
Using alarm() System Call to provideoperation timeout.
/* --- Alarm signal handler. --- */void catch_alarm(int sig_num){ perror("Operation timed out."); exit(0);}…/* --- Reads user name --- */int main(int argc, char* argv[]){ /* subscribe for ALRM signals */ signal(SIGALRM, catch_alarm); /* prompt the user for input */ printf("Username: "); fflush(stdout); /* start a 30 seconds alarm */ alarm(30); /* wait for user input */ fgets(userName, MAXBUFF, stdin);
/* remove the timer*/ alarm(0);
printf("User name: '%s'\n", userName); return 0;}
#include <unistd.h>
unsigned intalarm (unsigned int sec);
• Causes the system to generate a SIGALRM signal for the process after the number of sec real-time seconds.• If sec = 0, a pending alarm request, if any, is cancelled.• Alarm requests are not stacked. Each alarm() call reschedules the alarm time.• The fork() call clears pending alarms in the child process.
This is a defect of Process functionality, when behavior of the process
is unexpectedly and critically depends on the sequence or timing of occurring events.
Most common scenario: two events (or signals) are racing each other to affect the Process.
This is Critical Region
void sigreact (int sig){ flag = ! flag;}void someProcedure(){… flag = 1; /* subscribe to signal */ signal (SIGINT, sigreact);…… /* wait for signal */ while(flag) { pause ( ); } /* continue execution */…
If signal arrives here, flag will be changed to 0, pause() call will not be performed,process execution will continue
If signal arrives here, flag will be changed to 0, pause() call will be interrupted,and process execution will continue
If signal arrives after check of flag flag will be changed to 0, but pause() call will be performed,process will be “stuck”
Race Condition Example
Two “racing” events are:
• Flag testing by procedure
• Flag setting by signal handler
Critical Region
This is the region of code, where occuring of event (or signal) causes Race Condition.
Avoiding of Race ConditionThere are two ways to avoid Race Condition :
1) To perform the Polling - repeatable check of the resource state with limited time period
In previous example this means to replace system call pause( ) with call to function sleep(int seconds).
Advantage:
This is the simplest way to avoid process forever “sticking”.
Disadvantage:
In certain condition, process will be able to recognize state update only after delay .
In previous example, if signal will occur after flag check, but before sleep() call, the process will
be able to recognize flag update only after expiration of next sleep timeout
2) To provide Blocking of event (signal) delivery in the Critical Region.
In previous example this means to prohibit delivery of specific signal SIGINT between flag check and
system call pause( ).
Advantage:
The event (signal) delivery delay will be minimized.
Event (signal) will be delivered as soon as Critical Region will be passed.
Disadvantage:
Requires more complicated blocking mechanism to be provided by Kernel
Note:In most the cases the Race Condition occurs between test and set operations.To avoid “racing” of test and set, the Kernel provides number of tools (system calls),performing test-and-set as one impartible operation.
POSIX System Calls for Signal Blocking#include <signal.h>int sigprocmask (int how, const sigset_t *set, sigset_t *oldset);
• System call sigprocmask() is used to change / examine the Signal Mask (set of blocked signals) of the calling process• Parameter how may have the following values
-SIG_BLOCK - the Signal Set, specified by set, is added to process Signal Mask-SIG_UNBLOCK - the Signal Set, specified by set, is removed from process Signal Mask-SIG_SETMASK - the Signal Set, specified by set, replaces the process Signal Mask
• If oldset is not NULL, the old Signal Mask value is returned• If set is NULL, the process Signal Mask is not modified.• If any pending signals became unblocked during the call, at least one of those signals will be delivered before the call to sigprocmask() returns.• Attempts to block signals SIGKILL, SIGTOP are silently ignored.• Return values: 0-success, -1 failure (errno will specify the error).
• System call sigsuspend() performs the following operations:
- temporary replaces Signal Mask;
- suspends the calling process until it receives a signal;
- restores the Signal Mask ,
if process is not terminated by signal.• If process is not terminated, returns -1 and sets errno = EINTR
Commonly the sigprocmask() call is used to block Signal delivery in Critical Region.The sigsuspend() call is used to wait for the signal out of Critical Region.
flag = 1; /* subscribe to signal */ signal (SIGINT, sigreact);… /* block the signal */ sigprocmask (SIG_BLOCK, &blockMask, NULL);… /* wait for signal */ while(flag) { sigsuspend ( &unblockMask); } /* continue execution */…
If signal arrives here, flag will be changed to 0, then sigsuspend () will not be called,process execution will continue
Here signal is blocked.If it will arrive,Pending Signal MaskWill be updated, but signal will not be delivered.
Race Condition Resolution
Example
Critical RegionIs covered.
Here the signal (pending or generated)is safely handled
struct sigaction { void (*sa_handler)(int); sigset_t sa_mask; int sa_flags;};
• The sigaction() system call provides POSIX advanced (relatively to signal() ) interface, used to change the action taken by a process on receipt of a specific signal.• Parameter signum specifies the signal number. Parameters act and oldact specify the pointers to the structures, describing old and new action to be taken on specified signal delivery.• The structure sigaction specifies the following fields: sa_handler - the signal handling function sa_mask - a mask of signals which should be blocked during execution of the signal handler. (the signal which triggered the handler will also be blocked, unless the SA_NODEFER flag is used) sa_flags - specifies a set of flags used to modify the delivery of the signal (flags are combined with logical OR) Some of sa_flags values: SA_RESETHAND - Restore the signal action to the default state once the signal handler has been called. SA_RESTART - Provide restart of “slow” system calls, interrupted by signal . SA_NODEFER - Do not prevent the signal from being received from within its own signal handler. • Returns 0 – success,
-1 – failure (errno specifies the error).
void handler(int sig){…}…
struct sigaction newAction; newAction.sa_handler=handler; /* set the handler*/sigfillset(&newAction.sa_mask); /* block other signals during the handling */newAction.sa_flags = 0; /* no flags */if (sigaction(SIGUSR1, &newAction, NULL) < 0){…}
struct msgbuf { long mtype; /* message type, must be > 0 */ char mtext[1]; /* message data of any type and size, may be empty */};int msgsnd(int msqid, struct msgbuf *ptr, int length, int flag);
• Sends message to Queue with specified ID.• Parameter msqid specifies ID of existing Message Queue• Parameter ptr must point to any structure with positive long first field.• Parameter length specifies real size of message data in pointed structure (excluding 1st field)• Parameter flag could be 0 or IPC_NOWAIT.• Without IPC_NOWAIT flag, the system call blocks, when Message Queue has no room for the new message
(occurs if too many messages in Queue or system-wide)• Returns 0 on success, -1 on error (errno specifies the error)
Receive Message from Message Queue#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>
int msgrcv(int msqid, struct msgbuf *ptr, int length, long msgtype, int flags);
• Receives message from Queue with specified ID.• Parameter msqid specifies ID of existing Message Queue• Parameter ptr points to buffer for message storage.• Parameter length specifies maximal length of message data to be received. • Parameter msgtype:
0 - receive message of any type
>0 - receive message of specific msgtype
<0 - receive message with lowest type that <=abs(msgtype)• Parameter flag could have bits:
MSG_NOERROR - no error if message data exceeds specified length (data is truncated)
IPC_NOWAIT - non-blocking mode• If IPC_NOWAIT flag is not specified, the system call blocks if Message of specified msgtype does not exist
System call unblocks in following cases:
- message appeared in Queue
- Queue removed
- signal interrupt• Returns number of bytes stored into the buffer ptr, -1 on error (errno specifies the error)
struct sembuf { ushort_t sem_num; /* semaphore number, beginning from 0 */ short sem_op; /* semaphore operation */ short sem_flg; /* operation flags */
}; int semop(int semid, struct sembuf * pOps, size_t nOps);
• Performs set of operations on Semaphore set with specified ID.• Parameter pOps is array of structures, one structure per operation.• Parameter nOps is array length.• Operation type is specified by sem_op field and has the following meaning:
sem_op > 0 : Semaphore[sem_num] += sem_op;
sem_op = 0 : wait while (Semaphore[sem_num] != 0);
• Field sem_flg could contain the following bit flags:
IPC_NOWAIT – operation to be performed in non-blocking mode
SEM_UNDO – individual operation in the array to be rolled back when the process exits • All set of operations, specified by array, is performed by Kernel as one impartible “atomic” operation.
The execution rule is “all or nothing”: if one of operation fails, all other operations in array are not performed.• The system call semop() blocks (unless the IPC_NOWAIT flag is set), and remains blocked until:
- the semaphore operations can all finish, so the call succeeds, - the process receives a signal, or - the semaphore set is removed.
• Returns 0 on success, -1 on error (errno specifies the error).
The Scenario:• We need stateful device with operations: non-blocking “send signal”, and impartible blocking “wait for signal”.• To avoid race condition (signal loss), the initial state of the device would be “waiting for signal” . The Solution:• “Waiting” state will correspond to 0 value of semaphore, “signal sending” will correspond to ++ operation.
Example 2: Binary Semaphore as Resource Locking DeviceThe Scenario:• We need device with 2 states (locked / unlocked) and operations “lock” and “unlock”.• Operation “lock” would be impartible, working in blocking mode, if device already “lock”-ed by another process.• Initial state of device to be “unlocked” to avoid deadlocking forever in case of initialization failure.The Solution: “Unlocked” state will correspond to 0 value of semaphore, “locked” state will correspond to value 1.
int semLock(int semID, int semN) /* wait while (Semaphore[semN] !=0 ); */{ /* Semaphore[semN]++; // i.e. = 1 */ struct sembuf pOps[2]; pOps[0].sem_num = semN; pOps[0].sem_op = 0; pOps[0].sem_flg = 0; /* IPC_NOWAIT to be used for non-blocking mode*/ pOps[1].sem_num = semN; pOps[1].sem_op = 1; pOps[1].sem_flg = SEM_UNDO; /* roll-back the operation on process exit */ return semop(semID, pOps, 2);}
int semUnlock(int semID, int semN) /* Semaphore[semN] --; // i.e. = 0 */{ /* would not require blocking */ struct sembuf pOps[1]; pOps[0].sem_num = semN; pOps[0].sem_op = -1; pOps[0].sem_flg = IPC_NOWAIT|SEM_UNDO; /* no block + roll-back on exit */ return semop(semID, pOps, 1);}
Note:
Locking “forever” by unexpectedly terminated process is avoided by usage of SEM_UNDO flag
Control Operations on Semaphore Set#include <sys/types.h>#include <sys/ipc.h>#include <sys/sem.h>
union semun { int val; /* for SETVAL */ struct semid_ds *buf; /* for IPC_STAT, IPC_SET */ unsigned short *array; /* for GETALL, SETALL */};int semctl (int semid, int semNum, int cmd, … /*union semun arg*/);
• Performs control operations on Semaphore set• Parameter cmd could have the following values: IPC_STAT - copy Semaphore set info to arg.buf IPC_SET - update Semaphore set permissions and ownership from arg.buf GETALL,SETALL - get / set semaphore semval values using arg.array (on set adjustment roll-back values are cleared in all processes, blocked processes are unblocked) SETVAL - set semval value of semaphore number semNum to be equal val. (adjustment roll-back value is cleared in all processes, blocked processes are unblocked) GETVAL,GETPID,GETNCNT, GETZCNT - return corresponded values for semaphore number semNum IPC_RMID - remove Semaphore set (unblocking any blocked processes)• Returns actual value for getter methods, 0 on success for others, -1 on error (errno specifies the error)
POSIX SemaphoresPOSIX provides it’s own standard of Semaphore as Inter-Process or Inter-Thread synchronization device.POSIX Semaphore is single non-negative integer counter with only 2 possible operations: • Post – Semaphore+=1 (analog of System 5 sem_op=1)• Wait – wait while (Semaphore == 0); Semaphore -=1; (analog of System 5 sem_op=-1)POSIX defines 2 forms of Semaphores: Named and Unnamed.
#include <semaphore.h> sem_t *sem_open(const char *name, int oflag, …/*mode_t permissions, unsigned int value*/);
• Creates new or opens already existing Named Semaphore, identified by Full Path name , beginning from “/”.• Parameter oflag could be combined from binary flags O_CREAT, O_EXCL (see call open() ).• For newly-created Semaphore octal permissions and initial value are required.• Returns pointer to Semaphore on success, SEM_FAILED constant on failure (errno specifies error).
int sem_close(sem_t *sem);
• Closes the Named Semaphore. • Returns 0 on success, -1 on failure.
int sem_unlink(const char *name);
• Removes Named Semaphore. The name is removed immediatelly. Semaphore object is destroyed when sem_close()-d by all processes.• Returns 0 on success, -1 on failure.
int sem_init(sem_t *sem, int pshared, unsigned int value);
• Initializes new Unnamed Semaphore in address sem with initial value for Inter-Process (pshared =1, sem points to shared memory) or for Inter-Thread (pshared =0) synchronization.• Returns 0 on success, -1 on failure.
int sem_destroy(sem_t *sem);
Unnamed Semaphore – memory-based semaphore allocated in memory shared by multiple processes or threads.
• Destroys the Unnamed Semaphore pointed by sem. • Returns 0 on success, -1 on failure.
Named Semaphore – identified by pathname, visible by multiple processes
Semaphore Operations: Post and Wait
int sem_post(sem_t *sem);
• Increments (unlocks) the Semaphore sem.• Returns 0 on success, -1 on failure.
int sem_wait(sem_t *sem);
• Waits until Value of Semaphore sem becomes positive, then decrements (locks) the semaphore.• Returns 0 on success, -1 on failure.
void *mmap(void *start, size_t length, int prot , int flags, int fd, off_t offset);
• Maps a file of specified length, pointed by open descriptor fd,
into the current process memory, pointed by start (may be NULL), beginning from specified offset.
The memory divided into pages (4K). Each page loaded from file once, when was accessed at first time.• Parameter prot specifies the permissions (protection mode - what could be done with segment),
and could have the following values:
PROT_EXEC, PROT_READ, PROT_WRITE, PROT_NONE • Parameter flags describes the memory sharing modes and visibility:
MAP_FIXED, MAP_SHARED, MAP_PRIVATE, MAP_ANONYMOUS
When map is shared, it could be attached by multiple processes in the same time.• Returns pointer to mapped memory or -1 in case of problem (errno specifies the error)
int msync(const void *start, size_t length, int flags);
• Synchronizes memory with source file. When shared segment is modified, the changes do not appear in the file until msync() is called.
int mprotect(const void *addr, size_t len, int prot);
• Modifies the protection mode of the shared memory