SlideShare a Scribd company logo
Linux System
Programming
Semaphores, Shared Memory,
and Message Queues
Engr. Rashid Farid Chishti
chishti@iiu.edu.pk
https://youtube.com/rfchishti
https://sites.google.com/site/chishti
 To communicate between different processes (inter-process communication or
IPC) we used Signals and Pipes.
 Other methods for IPC are (a) Message Queues (b) Shared memory and (c)
Semaphores.
 Message Queues: Information to be communicated is placed in a predefined
message structure. The process generating the message specifies its type and
places the message in a system-maintained message queue.
 Processes accessing the message queue can use the message type to
selectively read messages of specific types in a first in first out (FIFO) manner.
 Message queues provide the user with a means of asynchronously
multiplexing data from multiple processes.
Introduction to IPC
 Shared Memory: Information is communicated by accessing shared process
data space. This is the fastest method of inter-process communication.
 Shared memory allows participating processes to randomly access a shared
memory segment.
 Semaphores are often used to synchronize the access to the shared memory
segments.
 Semaphores: Semaphores are system-implemented data structures used to
communicate small amounts of data between processes. Most often,
semaphores are used for process synchronization.
 All three of these facilities can be used by related and unrelated processes, but
these processes must be on the same system (machine).
Introduction to IPC
Summary of the System V IPC Calls
Functionality
Message
Queue
Semaphore
Shared
Memory
Allocate an IPC resource; gain access to an
existing IPC resource.
msgget Semget Shmget
Control an IPC resource: obtain / modify status
information, remove the resource.
msgctl Semctl Shmctl
send / receive messages, perform semaphore
operations, attach / free a shared memory
segment.
msgsnd
Msgrcv
Semop
Shmat
Shmdt
Programming interface for message queue
Initializing a message queue
 The function msgget() creates and accesses a Message Queue
#include <sys/msg.h>
#include <sys/ipc.h>
int msgget(key_t key, int msgflg);
Function msgget() returns a positive integer, as a message queue identifier.
Parameters:
Key: an arbitrary integer number;
msgflg: the permission mode and creation control flag.
Message Queue
#include <sys/msg.h> #include <sys/ipc.h>
#include <sys/types.h> #include <unistd.h>
#include <errno.h> #include <stdio.h>
#include <stdlib.h>
int main() {
key_t key = 1234; // key to be passed to msgget()
int msgflg = 0666 | IPC_CREAT; // msgflg to msgget()
int msgid; // return value from msgget()
// read and write permission for owner, and create a message
// queue if not exists
if ((msgid = msgget(key, msgflg))== -1) {
perror("msgget: msgget failed"); exit(-1);
}
else {
printf("Created a MSG Queue %d with key %x n", msgid, key);
exit(0);
}
}
Creating a Message Queue msgq_create.c
Message Queue
 Function msgctl() alters the permissions and other characteristics of a message queue.
int msgctl(int msgid, int cmd, struct msgid_ds *buf )
 It returns 0 on success, -1 for failure.
 Parameters:
msgid: message identifier, which is the return value from msgget().
struct msgid_ds {
uid_t msg_perm.uid;
uid_t msg_perm.gid;
mode_t msg_perm.mode;
}
Message Queue Settings
 cmd: the action to take, can be one of the following settings:
 IPC_STAT: Place information about the status of the queue in the data
structure pointed to by buf. The process must have read permission for this
call to succeed.
 IPC_SET: Set the owner's user ID (msg_perm.uid) and group ID
(msg_perm.gid), the permissions (msg_perm.mode) , and the size
(msg_qbytes) of the message queue. A process must have the effective user ID
of the owner, creator, or super user for this call to succeed.
 IPC_RMID: Remove the message queue.
Message Queue Settings
#include <sys/msg.h> #include <sys/ipc.h>
#include <sys/types.h> #include <unistd.h>
#include <errno.h> #include <stdio.h>
#include <stdlib.h>
int main() {
key_t key = 1234; int msgflg = 0666 | IPC_CREAT; int msgid;
if ((msgid = msgget(key, msgflg))== 1) {
perror("msgget: msgget failed"); exit(-1);
}
else { printf("msgget succeededn");
if(msgctl(msgid, IPC_RMID, 0) == -1) {
perror("msgctl: msgctl failed"); exit(-2);
}
else {
printf("msgctl succeededn"); exit(0);
}
}
}
Creating and Removing a Message Queue msgq_remove.c
// msgq_ctl.c Displaying message queue status information
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int main () {
int mgid; key_t key = 1234;
struct msqid_ds buf;
if ((mgid = msgget (key, IPC_CREAT | 0660)) == -1) {
perror ("Queue create"); return 1;
}
msgctl (mgid, IPC_STAT, &buf);
printf("Message Queue *Permission* Structure Informationn");
printf("Owner's user ID t %d n", buf.msg_perm.uid);
printf("Owner's group ID t %d n", buf.msg_perm.gid);
printf("Creator's user ID t %d n", buf.msg_perm.cuid);
printf("Creator's group IDt %d n", buf.msg_perm.cgid);
printf("Access mode in Octal t %o n", buf.msg_perm.mode);
Showing Status of a Message Queue msgq_ctl.c
printf("nAdditional Selected Message Queue Structure Informationn");
printf("Current # of bytes on queue t %d n", buf.__msg_cbytes);
printf("Current # of messages on queuet %d n", buf.msg_qnum);
printf("Maximum # of bytes on queue t %d n", buf.msg_qbytes);
msgctl (mgid, IPC_RMID, (struct msqid_ds *) 0);
return 0;
}
Showing Status of a Message Queue msgq_ctl.c
 The msgsnd() and msgrcv() functions send and receive messages, respectively:
int msgsnd(int msgid, const void *msgp, size_t msgsz, int msgflg);
int msgrcv(int msgid, void *msgp, size_t msgsz, long msgpriori,
int msgflg);
 Parameters
msgp: a pointer to a structure that contains the type of the message and its text. The
structure below is an example of what this user-defined buffer might look like:
struct mymsg {
long msgtype; /* message type */
char mtext[MSGSZ]; /* message text of length MSGSZ */
}
Sending and Receiving Message
 The structure member msgtype is used in message reception, must be initialized (into a
integer value) by the sending process.
 msgsz: specifies the length of the message in bytes.
 msgpriori: reception priority. Set 0 means you simply want to retrieve the message in the
order in which they were sent. Or some other values must be equal to the specified
message type.
 msgflg: for msgsnd(), controls what happens if either the queue is full, or reaches the
system limit on queued messages. Set as 0 means process suspends and wait for the space
become available.
 msgflg: for msgrcv(), controls what happens if no message of the proper priority is waiting
to be received. Set as 0 means process suspends and wait for an message with proper
priority to arrive.
Sending and Receiving Message
// Message Sending Program
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX_TEXT 512
struct my_msg_st/* define a message structure */
{
long int my_msg_type;
char some_text[MAX_TEXT];
};
Sending a Message msgq_send.c
int main () {
int running = 1;
/* declare an instance of structure of my_msg_st */
struct my_msg_st some_data;
int msgid; /* return value from msgget() */
char buffer[BUFSIZ]; /* declare a buffer for text msg */
// read and write permission for owner, and create a
// message queue if not exists
msgid = msgget ((key_t) 1234, 0666 | IPC_CREAT);
if (msgid == -1) {
fprintf (stderr, "msgget failed with error: %dn", errno);
exit (EXIT_FAILURE);
}
Sending a Message msgq_send.c
while (running) { /*read user input from the keyboard */
printf ("Enter some text: ");
fgets (buffer, BUFSIZ, stdin);
some_data.my_msg_type = 1; /*set the msgtype */
/*copy from buffer to message*/
strcpy (some_data.some_text, buffer);
/*send the message */
if (msgsnd (msgid, (void *) &some_data, MAX_TEXT, 0) == -1)
{
fprintf (stderr, "msgsnd failedn");
exit (EXIT_FAILURE);
}
if (strncmp (buffer, "end", 3) == 0)
{
running = 0;
}
}
exit (EXIT_SUCCESS);
}
Sending a Message msgq_send.c
/* the receiver program. */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct my_msg_st {
long int my_msg_type;
char some_text[BUFSIZ];
};
int main() {
int running = 1;
int msgid;
struct my_msg_st some_data;
long int msg_to_receive = 0;
Receiving a Message msgq_receive.c
/* First, we set up the message queue. */
msgid = msgget((key_t)1234, 0666 | IPC_CREAT);
if (msgid == -1) {
fprintf(stderr, "msgget failed with error: %dn", errno);
exit(EXIT_FAILURE);
}
/* Then the messages are retrieved from the queue,
until an end message is encountered. Lastly, the
message queue is deleted. */
while(running) {
if (msgrcv(msgid, (void *)&some_data, BUFSIZ,
msg_to_receive, 0) == -1) {
fprintf(stderr, "msgrcv failed with error: %dn", errno);
exit(EXIT_FAILURE);
}
printf("You wrote: %s", some_data.some_text);
if (strncmp(some_data.some_text, "end", 3) == 0) {
running = 0;
}
}
Receiving a Message msgq_receive.c
/* First, we set up the message queue. */
msgid = msgget((key_t)1234, 0666 | IPC_CREAT);
if (msgid == -1) {
fprintf(stderr, "msgget failed with error: %dn", errno);
exit(EXIT_FAILURE);
}
/* Then the messages are retrieved from the queue,
until an end message is encountered. Lastly, the
message queue is deleted. */
while(running) {
if (msgrcv(msgid, (void *)&some_data, BUFSIZ,
msg_to_receive, 0) == -1) {
fprintf(stderr, "msgrcv failed with error: %dn", errno);
exit(EXIT_FAILURE);
}
printf("You wrote: %s", some_data.some_text);
if (strncmp(some_data.some_text, "end", 3) == 0) {
running = 0;
}
}
Receiving a Message msgq_receive.c
if (msgctl(msgid, IPC_RMID, 0) == -1) {
fprintf(stderr, "msgctl(IPC_RMID) failedn");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
Receiving a Message msgq_receive.c
 Shared memory is an efficient way of transferring data between two running processes.
 It lets multiple processes attach to a segment of physical memory to their virtual address
spaces.
 If one process writes to a shared memory, the changes immediately become visible to any
other processes that has access to the same shared memory.
 The shared memory doesn't provide synchronization of accessing, we may use semaphore
to prevent inconsistencies and collisions
Shared Memory
Programming interface of Shared Memory
 The function shmget() is used to obtain access to a shared memory segment. It is
prottyped by:
int shmget(key_t key, size_t size,int shmflg);
Parameters:
key: an access value associated with the semaphore ID.
size: the size (in bytes) of the requested shared memory.
shmflg: specifies the initial access permissions and creation control flags.
A successful function call should return the shared memory segment ID, otherwise, returns
-1.
Shared Memory
#include <stdio.h>
#include <sys/shm.h>
int main ()
{
key_t key = 1234; // key to be passed to shmget()
size_t size = 4096; // size of shared memory
int shmflag = 0666 | IPC_CREAT; // read and write permission,
// create shared memory if not exist
int shmid; // return value from shmget()
// Create the shared memory segment using key 1234
shmid = shmget (key, size, shmflag);
if (shmid >= 0){
printf ("Created a shared memory segment %d using key %x n", shmid, key);
}
return 0;
}
Creating a Shared Memory shm_create.c
Creating a Shared Memory
 The function shmctl() is used to alter the permissions and other characteristics of a shared
memory segment. It is prototyped as follows:
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
 The process must have an effective shmid of owner, creator or super user to perform this
command.
Parameters: cmd argument is one of following control commands:
 SHM_LOCK: Lock the specified shared memory segment.
 SHM_UNLOCK: Unlock the shared memory segment.
 IPC_STAT: Return the status information contained in the control structure and place it
in the buffer pointed to by buf.
 IPC_SET: Set the effective user and group identification and access permissions.
 IPC_RMID: Remove the shared memory segment.
Shared Memory Settings
 The buf is a pointer to a type structure, struct shmid_ds which is defined in < sys/shm.h >
struct shmid_ds {
struct ipc_perm shm_perm; /* permissions */
size_t shm_segsz; /* size of segment in bytes */
pid_t shm_lpid; /* pid of last shmop() */
pid_t shm_cpid; /* pid of creator */
shmatt_t shm_nattch; /* number of current attaches */
time_t shm_atime; /* last-attach time */
time_t shm_dtime; /* last-detach time */
time_t shm_ctime; /* last-change time */
.
.
};
Shared Memory Settings
 shmat() and shmdt() are used to attach and detach shared memory segments. They are
prototypes as follows:
void *shmat(int shmid, const void *shmaddr, int shmflg);
int shmdt(const void *shmaddr);
 shmat() returns a pointer, shmaddr, to the head of the shared segment associated with a
valid shmid.
 shmdt() detaches the shared memory segment located at the address indicated by
shmaddr.
Attaching and detaching a Shared Memory
#include <stdio.h>
#include <time.h> // for ctime()
#include <sys/shm.h>
#include <errno.h>
int main(){
key_t key = 1234; // key to be passed to shmget()
size_t size = 4096; // size of shared memory
int shmflag = 0666 | IPC_CREAT; // read and write permission,
// create shared memory if not exist
int shmid; // return value from shmget()
int ret; // return value from shmctl()
struct shmid_ds shmds; // structure to store information
// about shared memory
// Create the shared memory segment using key 1234
shmid = shmget( key, size, shmflag );
Showing Status of a Shared Memory shm_status.c
if ( shmid >= 0 ) {
ret = shmctl( shmid, IPC_STAT, &shmds );
if (ret == 0) {
printf( "Size of memory segment is %ldn", shmds.shm_segsz);
printf( "Number of attaches %ldn", shmds.shm_nattch );
printf( "Access permissions %on", shmds.shm_perm.mode );
printf( "Create time %ld n", shmds.shm_ctime);
printf( "Create time %s n", ctime(&shmds.shm_ctime));
}
else {
printf( "shmctl failed (%d)n", errno );
}
}
else {
printf( "Shared memory segment not found.n" );
}
return 0;
}
Showing Status of a Shared Memory shm_status.c
#include <stdio.h>
#include <sys/shm.h>
#include <errno.h>
#include <time.h>
int main(){
int shmid, ret;
struct shmid_ds shmds;
shmid = shmget( 1234, 0, 0 );
if ( shmid >= 0 ) {
ret = shmctl( shmid, IPC_STAT, &shmds );
if (ret == 0) {
printf("old permissions were %on", shmds.shm_perm.mode );
shmds.shm_perm.mode = 0444;
ret = shmctl( shmid, IPC_SET, &shmds );
ret = shmctl( shmid, IPC_STAT, &shmds );
printf("new permissions are %on", shmds.shm_perm.mode );
ret = shmctl( shmid, SHM_LOCK, 0 );
ret = shmctl( shmid, SHM_UNLOCK, 0 );
}
Changing Permission of a Shared Memory shm_perm.c
else {
printf( "shmctl failed (%d)n", errno );
}
}
else {
printf( "Shared memory segment not found.n" );
}
return 0;
}
Changing Permission of a Shared Memory shm_perm.c
#include <stdio.h>
#include <sys/shm.h>
#include <errno.h>
int main(){
int shmid, ret;
void *mem; // Get the shared memory segment using 1234
shmid = shmget(1234, 0, 0 );
if ( shmid >= 0 ) {
mem = shmat( shmid, (const void *)0, 0 );
if ( mem > 0 ) {
printf( "Shared Memory starting address is %pn", mem );
ret = shmdt(mem);
if(ret == 0){
printf("Successfully detached memoryn");
}
else { printf("Memory detached Failed (%d)n", errno); }
}
}
}
Detaching from a Shared Memory shm_detach.c
#include <stdio.h>
#include <sys/shm.h>
#include <string.h>
int main(){
int shmid, ret;
void *mem;
shmid = shmget( 1234, 4096, 0666 | IPC_CREAT );
// Attach to Shared Mamory
mem = shmat( shmid, (const void *)0, 0 );
// Write to Shared Memory
strcpy( (char *)mem, "This is a test string.n" );
printf( "%s", (char *)mem ); // Read from Shared Memory
// Detach from Shared Mamory
ret = shmdt( mem );
return 0;
}
Writing and Reading from a Shared Memory shm_rw.c
#include <stdio.h>
#include <sys/shm.h>
#include <errno.h>
int main(){
int shmid, ret;
shmid = shmget( 1234, 0, 0 );
if ( shmid >= 0 ) {
ret = shmctl( shmid, IPC_RMID, 0 );
if (ret == 0) {
printf( "Shared memory segment removedn" );
}
else {
printf( "shmctl failed (%d)n", errno );
}
}
else { printf( "Shared memory segment not found.n" ); }
return 0;
}
Removing a Shared Memory shm_rm.c
Introduction to Semaphores
 Semaphores are used to avoid race condition. Therefore, Semaphores are
control mechanism.
 Race condition occurs when two or more processes are in their critical section.
 Critical section is a part of code in which a process accesses a shared
resource.
 So whenever two or more processes in their critical sections, their may be
chances that they might go in race condition.
 A semaphore is a data structure, which can be shared by a group of processes.
 When several processes compete for same resource (e.g. a file, a message
queue, or a shared memory), their operations may be synchronized with the
use of semaphores, so that they do not interfere with each other.
Semaphores
 Semaphores ensure that only one process will be granted exclusive access of a
particular resource.
 All other processes requiring the same resource will be suspended by Linux
kernel.
 Once a process releases the resource, the kernel will grant exclusive access of
the resource to a suspended process.
 Semaphores are often used in pair in order to lock (protect) a resource and to
subsequently unlock (release) a resource.
Semaphores
 Controlling the synchronization using an abstract data type called a semaphore was
proposes by by Dijksta in1965.
 A Semaphore S is a an integer variable that can be accesses only through two atomic
operations.
i.e. these operation can not be interrupted and can be treated as an indivisible step.
Operation Semaphore Dutch Meaning
Wait P proberen to test
Signal V verhogen to increment
Semaphores
wait(S) {
while (S<=0);
S--;
}
signal (S) {
S++;
}
 At its simplest a semaphore is variable S which takes one of two values:
 0 when a resource is locked (protected), and should not be accessed by
other processes
 1 when the resource is unlocked (released).
 Such semaphore, which could take two values 0 or 1, is called binary
semaphore.
 But in Linux implementation the two values are
 –1, which is our P operation to wait for a semaphore to become available
 +1, which is our V operation to signal that a semaphore is now available.
Semaphores
 As we know that a semaphore is a variable, so before performing any
operation on semaphore it must exist. The semget call creates a set of
semaphore along with its associated data structure (or gets an existing
semaphore ) It is prototyped by:
#include <sys/sem.h>
#include <sys/ipc.h>
#include <sys/types.h>
int semget(key_t key, int nsems, int semflg);
When the call succeeds, it returns the semaphore ID (semid). otherwise it
returns –1, if call fails.
Creating a new semaphores
Parameters
 key: is a access value associated with the semaphore ID.
 nsems: the number of semaphores required (since UNIX provides an array of
individual semaphores, to give control of multiple resources).
 Setting it 1, means create one semaphore in a set.
 semflg: specifies the initial access permissions and creation control flags.
 This will be zero if the semaphore already exists
 If not it should be like IPC_CREAT | 0666
 Please Note, the initial value of a semaphore is zero when it is created first
time.
Creating a new semaphores
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
int main(){
key_t key = 1234; // key to pass to semget()
int semflg = 0666 | IPC_CREAT; // semflg to pass to semget()
int nsems = 1; // nsems to pass to semget()
int semid; //return value from semget()
if((semid = semget(key, nsems, semflg)) ==-1){
perror("semget: semget failed");
exit(-1);
}
printf( "semget Created a semaphore with id = %d n", semid );
return 0;
}
Removing a Shared Memory sem_create.c
Controlling Semaphores
 Function semctl() changes permissions and other characteristics of a
semaphore set. It's prototype is as followed:
int semctl(int semid,int semnum,int cmd, union semun sem_union);
 It returns different values depending on the cmd.
 For setting the value of a single semaphore or removing the semaphore set, it
returns 0 on success, -1 for failure.
Parameters:
 semctl must be called with a valid semaphore ID, semid.
 The semnum value selects a semaphore within an array by its index.
 To access first semaphore its values is 0.
Creating a new semaphores
 All the control operations on the set of semaphores, which are identified by semaphores ID
semid are specified by third the argument cmd.
 The parameters cmd can take the values are given by:
 GETVAL: Returns the semaphore’s value.
 SETVAL: Set the semaphore value given in sem_union
 GETPID: Get PID of the process that last called semop.
 IPC_STAT: Return the effective user, group, and permission for a semaphore in
sem_union.
 IPC_RMID: Remove the specified semaphore set with semid along with its associated
data structure.
 If the semctl call fails, it returns –1, otherwise it returns an integer value of depending on
the value of cmd.
Creating a new semaphores
#include <stdio.h>
#include <sys/sem.h>
#include <stdlib.h>
int main(){
int semid, cnt;
semid = semget( 1234, 1, 0 ); // Get the semaphore with the key 1234
if (semid >= 0) {
// Read the current semaphore count. Index of semaphore is
// 0. The command is GETVAL. The return value from this
// command is either –1 for error or the count of the
// semaphore.
cnt = semctl( semid, 0, GETVAL );
if (cnt != -1) {
printf("semcrd: current semaphore count %d.n", cnt);
}
}
return 0;
}
Semaphore: Get Current Count sem_getval.c
// Setting the Current Semaphore Count
#include <stdio.h>
#include <sys/sem.h>
#include <stdlib.h>
int main(){
int semid, ret;
/* Get the semaphore with the key 1234 */
semid = semget( 1234, 1, 0 );
if (semid >= 0) {
// Set the semaphore No.0 to a value 6, changing the binary
// semaphore to a counting semaphore
ret = semctl( semid, 0, SETVAL, 6);
if (ret != -1) {
printf("current semaphore count updated n");
}
}
return 0;
}
Semaphore: Set Count sem_setval.c
#include <stdio.h>
#include <sys/sem.h>
#include <stdlib.h>
int main() {
int semid, ret;
/* Get the semaphore with the key 1234 */
semid = semget( 1234, 1, 0 );
if (semid >= 0) {
/* Remove Semaphore having id semid */
ret = semctl( semid, 0, IPC_RMID);
if (ret != -1) {
printf("Semaphore %d removed.n", semid );
}
}
return 0;
}
Removing a Semaphore sem_rm.c
 The semop() API function provides the means to acquire and release a
semaphore or semaphore array.
 The basic operations provided by semop are
 Decrement semaphore (to acquire semaphores)
 Increment a semaphore (to release semaphores).
It is prototyped by:
int semop(int semid , struct sembuf *sops , unsigned int nsops);
Parameters:
 semid: the semaphore ID returned by semget() call.
 sops: is a pointer to an array of structures, each containing the following
information about a semaphore operation:
Semaphore Operations
 The semaphore number of interest sem_num, usually 0 means first
semaphore from an array.
 The operation to be performed sem_op, is the value by which the
semaphore should be changed. (You can change a semaphore by amounts
other than 1.) In general, only two values are used,
 –1, which is your P operation to wait for a semaphore to become
available
 +1, which is your V operation to signal that a semaphore is now available.
 a flags word sem_flg can be used to alter the behavior of the operation.
usually set to SEM_UNDO means if the process terminates without releasing
the semaphore, allows the operating system to automatically release the
semaphore.
Semaphore Operations
 The sembuf structure is shown below:
struct sembuf {
unsigned short sem_num;
short sem_op;
short sem_flg;
};
 nsops: Number of semaphores in the array
Semaphore Operations
#include <sys/types.h> #include <sys/ipc.h>
#include <sys/sem.h> #include <unistd.h>
#include <errno.h> #include <stdio.h>
int main() {
int semid; struct sembuf sb; semid = semget( 1234, 1, 0 );
if (semid >= 0){ /* build semaphore operations structure */
sb.sem_num = 0; /*semaphore number,0 for first semaphore */
sb.sem_op = -1; /* operation -1 means acquire semaphore */
sb.sem_flg = 0; /* operation flags*/
printf( "Attempting to acquire semaphore %dn", semid );
if ( semop( semid, &sb, 1 ) == -1 ) { /* if the value of
a semaphore is 0 this will wait until it becomes > 0 */
printf( "semacq: semop failed.n" ); exit(-1);
}
printf( "semacq: Semaphore acquired %dn", semid );
} return 0;
}
Getting a Semaphore sem_acquire.c
#include <sys/types.h> #include <sys/ipc.h>
#include <sys/sem.h> #include <unistd.h>
#include <errno.h> #include <stdio.h>
int main() {
int semid; struct sembuf sb;
semid = semget( 1234, 1, 0 );
if (semid >= 0){ /* build semaphore operations structure */
sb.sem_num = 0; /*semaphore number,0 for first semaphore */
sb.sem_op = 1; /* operation +1 means release semaphore */
sb.sem_flg = 0; /* operation flags*/
printf( "Releasing a semaphore %dn", semid );
if ( semop( semid, &sb, 1 ) == -1 ){
printf( "semacq: semop failed.n" ); exit(-1);
}
printf( "semacq: Semaphore released %dn", semid );
} return 0;
}
Releasing a Semaphore sem_release.c
Examples
/* waiting P(sv): */
static int semaphore_p(void){
struct sembuf sem_b;
sem_b.sem_num = 0; /* first semaphore */
sem_b.sem_op =-1; /*P(sv)*/
sem_b.sem_flg =0;
if(semop(semid, &sem_b , 1 ) == -1){
perror("semop: semop failed");
return(0);
}
return(1);
}
Semaphore Operations
Examples
/* giving controll V(sv) */
static int semaphore_v(void){
struct sembuf sem_b;
sem_b.sem_num = 0; /* first semaphore */
sem_b.sem_op = 1; /*V(sv)*/
sem_b.sem_flg =0;
if(semop(semid, &sem_b, 1) == -1){
perror("semop: semop failed");
return(0);
}
return(1);
}
Semaphore Operations
Examples
/* giving controll V(sv) */
static int semaphore_v(void){
struct sembuf sem_b;
sem_b.sem_num = 0; /* first semaphore */
sem_b.sem_op = 1; /*V(sv)*/
sem_b.sem_flg =0;
if(semop(semid, &sem_b, 1) == -1){
perror("semop: semop failed");
return(0);
}
return(1);
}
Semaphore Operations
Q 1. Write a client Server application in C using message queues in which the client
takes an integer from the user and sends this integer to the server through message
queue, for computation of its factorial.
The client program should return message queue ID, so that you could use this ID
when you run the server.
Q 2. Write a client Server application in C using message queues in which the client
takes Linux command from the user and sends this command to the server through
message queue, for execution of Linux command.
The server takes that command through message queue and executes this
command.
Assignment Topic: Message Queues
Q 3. Write Client and Server programs in C using the concept of shared memory. If for
example, the client program writes an integer n in the shared memory, server reads this
integer n from the shared memory, and prints this integer n number of time. The server
program should be terminated if it reads a negative integer from the shared memory.
Q 4. Write a Client & Server program in C using the concept of shared memory. The server
creates a shared memory segment to store its process ID. The client reads process ID of the
server. Using server process ID, the client program can raise signals SIGINT, SIGTSTP,
SIGQUIT (by using kill() system call), in such a way that when a user presses:
 i or I it raises signal SIGINT
 z or Z it raises signal SIGTSTP
 q or Q it raises SIGQUIT
 Error message if user presses any other character.
The server program should provide handlers for catching above signals. The server ignores
signals on receiving SIGINT, or SIGTSTP (use SIG_IGN for ignoring the signal). However, the
server program quits on receiving SIGQUIT. The client program also quits after sending
SIGQUIT signal.
Assignment Topic: Shared Memory
Q 5. Write a C-program, in which
1. first create an integer type of shared memory segment,
2. Then lock this segment through Semaphore, so that other processes cannot access it.
3. it writes a number in this shared segment.
4. Then unlock this segment through Semaphore so that other processes can access it.
Q 6. Write another C-program, in which
1. locks this segment through Semaphore first
2. Reads integer from shared memory
3. Unlocks semaphore
4. Prints integer on screen
Assignment

More Related Content

Similar to Linux Systems Programming: Semaphores, Shared Memory, and Message Queues

Inter Process Communication PPT
Inter Process Communication PPTInter Process Communication PPT
Inter Process Communication PPT
Sowmya Jyothi
 
Linux Systems Programming: Process CommunCh11 Processes and Signals
Linux Systems Programming: Process CommunCh11 Processes and SignalsLinux Systems Programming: Process CommunCh11 Processes and Signals
Linux Systems Programming: Process CommunCh11 Processes and Signals
RashidFaridChishti
 
Shell to be modified#include stdlib.h #include unistd.h .pdf
Shell to be modified#include stdlib.h #include unistd.h .pdfShell to be modified#include stdlib.h #include unistd.h .pdf
Shell to be modified#include stdlib.h #include unistd.h .pdf
clarityvision
 
Introduction to MPI
Introduction to MPIIntroduction to MPI
Introduction to MPI
yaman dua
 
Parallel computing(2)
Parallel computing(2)Parallel computing(2)
Parallel computing(2)
Md. Mahedi Mahfuj
 
Usp message queues
Usp message queuesUsp message queues
Usp message queues
RohitK71
 
httplinux.die.netman3execfork() creates a new process by.docx
httplinux.die.netman3execfork() creates a new process by.docxhttplinux.die.netman3execfork() creates a new process by.docx
httplinux.die.netman3execfork() creates a new process by.docx
adampcarr67227
 
25-MPI-OpenMP.pptx
25-MPI-OpenMP.pptx25-MPI-OpenMP.pptx
25-MPI-OpenMP.pptx
GopalPatidar13
 
Linux kernel debugging
Linux kernel debuggingLinux kernel debugging
Linux kernel debugging
Hao-Ran Liu
 
Usp
UspUsp
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Vincenzo Iozzo
 
Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2
Max Kleiner
 
Os lab final
Os lab finalOs lab final
Os lab final
LakshmiSarvani6
 
Help Needed!UNIX Shell and History Feature This project consists.pdf
Help Needed!UNIX Shell and History Feature This project consists.pdfHelp Needed!UNIX Shell and History Feature This project consists.pdf
Help Needed!UNIX Shell and History Feature This project consists.pdf
mohdjakirfb
 
ch 7 POSIX.pptx
ch 7 POSIX.pptxch 7 POSIX.pptx
ch 7 POSIX.pptx
sibokac
 
Message queue and shared memory
Message queue and shared memoryMessage queue and shared memory
Message queue and shared memory
NarayanlalMenariya
 
ipc.pptx
ipc.pptxipc.pptx
ipc.pptx
SuhanB
 
computer notes - Inter process communication
computer notes - Inter process communicationcomputer notes - Inter process communication
computer notes - Inter process communication
ecomputernotes
 
Threads Advance in System Administration with Linux
Threads Advance in System Administration with LinuxThreads Advance in System Administration with Linux
Threads Advance in System Administration with Linux
Soumen Santra
 
Trap Handling in Linux
Trap Handling in LinuxTrap Handling in Linux
Trap Handling in Linux
YongraeJo
 

Similar to Linux Systems Programming: Semaphores, Shared Memory, and Message Queues (20)

Inter Process Communication PPT
Inter Process Communication PPTInter Process Communication PPT
Inter Process Communication PPT
 
Linux Systems Programming: Process CommunCh11 Processes and Signals
Linux Systems Programming: Process CommunCh11 Processes and SignalsLinux Systems Programming: Process CommunCh11 Processes and Signals
Linux Systems Programming: Process CommunCh11 Processes and Signals
 
Shell to be modified#include stdlib.h #include unistd.h .pdf
Shell to be modified#include stdlib.h #include unistd.h .pdfShell to be modified#include stdlib.h #include unistd.h .pdf
Shell to be modified#include stdlib.h #include unistd.h .pdf
 
Introduction to MPI
Introduction to MPIIntroduction to MPI
Introduction to MPI
 
Parallel computing(2)
Parallel computing(2)Parallel computing(2)
Parallel computing(2)
 
Usp message queues
Usp message queuesUsp message queues
Usp message queues
 
httplinux.die.netman3execfork() creates a new process by.docx
httplinux.die.netman3execfork() creates a new process by.docxhttplinux.die.netman3execfork() creates a new process by.docx
httplinux.die.netman3execfork() creates a new process by.docx
 
25-MPI-OpenMP.pptx
25-MPI-OpenMP.pptx25-MPI-OpenMP.pptx
25-MPI-OpenMP.pptx
 
Linux kernel debugging
Linux kernel debuggingLinux kernel debugging
Linux kernel debugging
 
Usp
UspUsp
Usp
 
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
 
Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2
 
Os lab final
Os lab finalOs lab final
Os lab final
 
Help Needed!UNIX Shell and History Feature This project consists.pdf
Help Needed!UNIX Shell and History Feature This project consists.pdfHelp Needed!UNIX Shell and History Feature This project consists.pdf
Help Needed!UNIX Shell and History Feature This project consists.pdf
 
ch 7 POSIX.pptx
ch 7 POSIX.pptxch 7 POSIX.pptx
ch 7 POSIX.pptx
 
Message queue and shared memory
Message queue and shared memoryMessage queue and shared memory
Message queue and shared memory
 
ipc.pptx
ipc.pptxipc.pptx
ipc.pptx
 
computer notes - Inter process communication
computer notes - Inter process communicationcomputer notes - Inter process communication
computer notes - Inter process communication
 
Threads Advance in System Administration with Linux
Threads Advance in System Administration with LinuxThreads Advance in System Administration with Linux
Threads Advance in System Administration with Linux
 
Trap Handling in Linux
Trap Handling in LinuxTrap Handling in Linux
Trap Handling in Linux
 

More from RashidFaridChishti

Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docxLab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
RashidFaridChishti
 
Object Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docxObject Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docx
RashidFaridChishti
 
Lab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docxLab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docx
RashidFaridChishti
 
Data Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptxData Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptxData Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptxData Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptxData Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptxData Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptxData Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptxData Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptxData Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptxData Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptxData Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptxData Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptxData Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptxData Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptxData Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptxData Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptxData Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptx
RashidFaridChishti
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
RashidFaridChishti
 

More from RashidFaridChishti (20)

Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docxLab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
 
Object Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docxObject Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docx
 
Lab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docxLab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docx
 
Data Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptxData Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptx
 
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptxData Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptxData Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptx
 
Data Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptxData Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptx
 
Data Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptxData Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptx
 
Data Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptxData Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptx
 
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptxData Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
 
Data Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptxData Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptx
 
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptxData Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
 
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptxData Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
 
Data Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptxData Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptx
 
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptxData Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
 
Data Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptxData Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptx
 
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptxData Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
 
Data Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptxData Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptx
 
Data Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptxData Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptx
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
 

Recently uploaded

Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...
Prakhyath Rai
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
ijaia
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
nedcocy
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
Digital Twins Computer Networking Paper Presentation.pptx
Digital Twins Computer Networking Paper Presentation.pptxDigital Twins Computer Networking Paper Presentation.pptx
Digital Twins Computer Networking Paper Presentation.pptx
aryanpankaj78
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
Anant Corporation
 
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
PriyankaKilaniya
 
Generative AI Use cases applications solutions and implementation.pdf
Generative AI Use cases applications solutions and implementation.pdfGenerative AI Use cases applications solutions and implementation.pdf
Generative AI Use cases applications solutions and implementation.pdf
mahaffeycheryld
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
RamonNovais6
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
IJECEIAES
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
PreethaV16
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
bijceesjournal
 
Gas agency management system project report.pdf
Gas agency management system project report.pdfGas agency management system project report.pdf
Gas agency management system project report.pdf
Kamal Acharya
 
Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
bijceesjournal
 
TIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptxTIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptx
CVCSOfficial
 
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
upoux
 
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
upoux
 

Recently uploaded (20)

Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
Digital Twins Computer Networking Paper Presentation.pptx
Digital Twins Computer Networking Paper Presentation.pptxDigital Twins Computer Networking Paper Presentation.pptx
Digital Twins Computer Networking Paper Presentation.pptx
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
 
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
 
Generative AI Use cases applications solutions and implementation.pdf
Generative AI Use cases applications solutions and implementation.pdfGenerative AI Use cases applications solutions and implementation.pdf
Generative AI Use cases applications solutions and implementation.pdf
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
 
Gas agency management system project report.pdf
Gas agency management system project report.pdfGas agency management system project report.pdf
Gas agency management system project report.pdf
 
Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
 
TIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptxTIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptx
 
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
 
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
 

Linux Systems Programming: Semaphores, Shared Memory, and Message Queues

  • 1. Linux System Programming Semaphores, Shared Memory, and Message Queues Engr. Rashid Farid Chishti chishti@iiu.edu.pk https://youtube.com/rfchishti https://sites.google.com/site/chishti
  • 2.  To communicate between different processes (inter-process communication or IPC) we used Signals and Pipes.  Other methods for IPC are (a) Message Queues (b) Shared memory and (c) Semaphores.  Message Queues: Information to be communicated is placed in a predefined message structure. The process generating the message specifies its type and places the message in a system-maintained message queue.  Processes accessing the message queue can use the message type to selectively read messages of specific types in a first in first out (FIFO) manner.  Message queues provide the user with a means of asynchronously multiplexing data from multiple processes. Introduction to IPC
  • 3.  Shared Memory: Information is communicated by accessing shared process data space. This is the fastest method of inter-process communication.  Shared memory allows participating processes to randomly access a shared memory segment.  Semaphores are often used to synchronize the access to the shared memory segments.  Semaphores: Semaphores are system-implemented data structures used to communicate small amounts of data between processes. Most often, semaphores are used for process synchronization.  All three of these facilities can be used by related and unrelated processes, but these processes must be on the same system (machine). Introduction to IPC
  • 4. Summary of the System V IPC Calls Functionality Message Queue Semaphore Shared Memory Allocate an IPC resource; gain access to an existing IPC resource. msgget Semget Shmget Control an IPC resource: obtain / modify status information, remove the resource. msgctl Semctl Shmctl send / receive messages, perform semaphore operations, attach / free a shared memory segment. msgsnd Msgrcv Semop Shmat Shmdt
  • 5. Programming interface for message queue Initializing a message queue  The function msgget() creates and accesses a Message Queue #include <sys/msg.h> #include <sys/ipc.h> int msgget(key_t key, int msgflg); Function msgget() returns a positive integer, as a message queue identifier. Parameters: Key: an arbitrary integer number; msgflg: the permission mode and creation control flag. Message Queue
  • 6. #include <sys/msg.h> #include <sys/ipc.h> #include <sys/types.h> #include <unistd.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> int main() { key_t key = 1234; // key to be passed to msgget() int msgflg = 0666 | IPC_CREAT; // msgflg to msgget() int msgid; // return value from msgget() // read and write permission for owner, and create a message // queue if not exists if ((msgid = msgget(key, msgflg))== -1) { perror("msgget: msgget failed"); exit(-1); } else { printf("Created a MSG Queue %d with key %x n", msgid, key); exit(0); } } Creating a Message Queue msgq_create.c
  • 8.  Function msgctl() alters the permissions and other characteristics of a message queue. int msgctl(int msgid, int cmd, struct msgid_ds *buf )  It returns 0 on success, -1 for failure.  Parameters: msgid: message identifier, which is the return value from msgget(). struct msgid_ds { uid_t msg_perm.uid; uid_t msg_perm.gid; mode_t msg_perm.mode; } Message Queue Settings
  • 9.  cmd: the action to take, can be one of the following settings:  IPC_STAT: Place information about the status of the queue in the data structure pointed to by buf. The process must have read permission for this call to succeed.  IPC_SET: Set the owner's user ID (msg_perm.uid) and group ID (msg_perm.gid), the permissions (msg_perm.mode) , and the size (msg_qbytes) of the message queue. A process must have the effective user ID of the owner, creator, or super user for this call to succeed.  IPC_RMID: Remove the message queue. Message Queue Settings
  • 10. #include <sys/msg.h> #include <sys/ipc.h> #include <sys/types.h> #include <unistd.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> int main() { key_t key = 1234; int msgflg = 0666 | IPC_CREAT; int msgid; if ((msgid = msgget(key, msgflg))== 1) { perror("msgget: msgget failed"); exit(-1); } else { printf("msgget succeededn"); if(msgctl(msgid, IPC_RMID, 0) == -1) { perror("msgctl: msgctl failed"); exit(-2); } else { printf("msgctl succeededn"); exit(0); } } } Creating and Removing a Message Queue msgq_remove.c
  • 11. // msgq_ctl.c Displaying message queue status information #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> int main () { int mgid; key_t key = 1234; struct msqid_ds buf; if ((mgid = msgget (key, IPC_CREAT | 0660)) == -1) { perror ("Queue create"); return 1; } msgctl (mgid, IPC_STAT, &buf); printf("Message Queue *Permission* Structure Informationn"); printf("Owner's user ID t %d n", buf.msg_perm.uid); printf("Owner's group ID t %d n", buf.msg_perm.gid); printf("Creator's user ID t %d n", buf.msg_perm.cuid); printf("Creator's group IDt %d n", buf.msg_perm.cgid); printf("Access mode in Octal t %o n", buf.msg_perm.mode); Showing Status of a Message Queue msgq_ctl.c
  • 12. printf("nAdditional Selected Message Queue Structure Informationn"); printf("Current # of bytes on queue t %d n", buf.__msg_cbytes); printf("Current # of messages on queuet %d n", buf.msg_qnum); printf("Maximum # of bytes on queue t %d n", buf.msg_qbytes); msgctl (mgid, IPC_RMID, (struct msqid_ds *) 0); return 0; } Showing Status of a Message Queue msgq_ctl.c
  • 13.  The msgsnd() and msgrcv() functions send and receive messages, respectively: int msgsnd(int msgid, const void *msgp, size_t msgsz, int msgflg); int msgrcv(int msgid, void *msgp, size_t msgsz, long msgpriori, int msgflg);  Parameters msgp: a pointer to a structure that contains the type of the message and its text. The structure below is an example of what this user-defined buffer might look like: struct mymsg { long msgtype; /* message type */ char mtext[MSGSZ]; /* message text of length MSGSZ */ } Sending and Receiving Message
  • 14.  The structure member msgtype is used in message reception, must be initialized (into a integer value) by the sending process.  msgsz: specifies the length of the message in bytes.  msgpriori: reception priority. Set 0 means you simply want to retrieve the message in the order in which they were sent. Or some other values must be equal to the specified message type.  msgflg: for msgsnd(), controls what happens if either the queue is full, or reaches the system limit on queued messages. Set as 0 means process suspends and wait for the space become available.  msgflg: for msgrcv(), controls what happens if no message of the proper priority is waiting to be received. Set as 0 means process suspends and wait for an message with proper priority to arrive. Sending and Receiving Message
  • 15. // Message Sending Program #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #define MAX_TEXT 512 struct my_msg_st/* define a message structure */ { long int my_msg_type; char some_text[MAX_TEXT]; }; Sending a Message msgq_send.c
  • 16. int main () { int running = 1; /* declare an instance of structure of my_msg_st */ struct my_msg_st some_data; int msgid; /* return value from msgget() */ char buffer[BUFSIZ]; /* declare a buffer for text msg */ // read and write permission for owner, and create a // message queue if not exists msgid = msgget ((key_t) 1234, 0666 | IPC_CREAT); if (msgid == -1) { fprintf (stderr, "msgget failed with error: %dn", errno); exit (EXIT_FAILURE); } Sending a Message msgq_send.c
  • 17. while (running) { /*read user input from the keyboard */ printf ("Enter some text: "); fgets (buffer, BUFSIZ, stdin); some_data.my_msg_type = 1; /*set the msgtype */ /*copy from buffer to message*/ strcpy (some_data.some_text, buffer); /*send the message */ if (msgsnd (msgid, (void *) &some_data, MAX_TEXT, 0) == -1) { fprintf (stderr, "msgsnd failedn"); exit (EXIT_FAILURE); } if (strncmp (buffer, "end", 3) == 0) { running = 0; } } exit (EXIT_SUCCESS); } Sending a Message msgq_send.c
  • 18. /* the receiver program. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> struct my_msg_st { long int my_msg_type; char some_text[BUFSIZ]; }; int main() { int running = 1; int msgid; struct my_msg_st some_data; long int msg_to_receive = 0; Receiving a Message msgq_receive.c
  • 19. /* First, we set up the message queue. */ msgid = msgget((key_t)1234, 0666 | IPC_CREAT); if (msgid == -1) { fprintf(stderr, "msgget failed with error: %dn", errno); exit(EXIT_FAILURE); } /* Then the messages are retrieved from the queue, until an end message is encountered. Lastly, the message queue is deleted. */ while(running) { if (msgrcv(msgid, (void *)&some_data, BUFSIZ, msg_to_receive, 0) == -1) { fprintf(stderr, "msgrcv failed with error: %dn", errno); exit(EXIT_FAILURE); } printf("You wrote: %s", some_data.some_text); if (strncmp(some_data.some_text, "end", 3) == 0) { running = 0; } } Receiving a Message msgq_receive.c
  • 20. /* First, we set up the message queue. */ msgid = msgget((key_t)1234, 0666 | IPC_CREAT); if (msgid == -1) { fprintf(stderr, "msgget failed with error: %dn", errno); exit(EXIT_FAILURE); } /* Then the messages are retrieved from the queue, until an end message is encountered. Lastly, the message queue is deleted. */ while(running) { if (msgrcv(msgid, (void *)&some_data, BUFSIZ, msg_to_receive, 0) == -1) { fprintf(stderr, "msgrcv failed with error: %dn", errno); exit(EXIT_FAILURE); } printf("You wrote: %s", some_data.some_text); if (strncmp(some_data.some_text, "end", 3) == 0) { running = 0; } } Receiving a Message msgq_receive.c
  • 21. if (msgctl(msgid, IPC_RMID, 0) == -1) { fprintf(stderr, "msgctl(IPC_RMID) failedn"); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); } Receiving a Message msgq_receive.c
  • 22.  Shared memory is an efficient way of transferring data between two running processes.  It lets multiple processes attach to a segment of physical memory to their virtual address spaces.  If one process writes to a shared memory, the changes immediately become visible to any other processes that has access to the same shared memory.  The shared memory doesn't provide synchronization of accessing, we may use semaphore to prevent inconsistencies and collisions Shared Memory
  • 23. Programming interface of Shared Memory  The function shmget() is used to obtain access to a shared memory segment. It is prottyped by: int shmget(key_t key, size_t size,int shmflg); Parameters: key: an access value associated with the semaphore ID. size: the size (in bytes) of the requested shared memory. shmflg: specifies the initial access permissions and creation control flags. A successful function call should return the shared memory segment ID, otherwise, returns -1. Shared Memory
  • 24. #include <stdio.h> #include <sys/shm.h> int main () { key_t key = 1234; // key to be passed to shmget() size_t size = 4096; // size of shared memory int shmflag = 0666 | IPC_CREAT; // read and write permission, // create shared memory if not exist int shmid; // return value from shmget() // Create the shared memory segment using key 1234 shmid = shmget (key, size, shmflag); if (shmid >= 0){ printf ("Created a shared memory segment %d using key %x n", shmid, key); } return 0; } Creating a Shared Memory shm_create.c
  • 26.  The function shmctl() is used to alter the permissions and other characteristics of a shared memory segment. It is prototyped as follows: int shmctl(int shmid, int cmd, struct shmid_ds *buf);  The process must have an effective shmid of owner, creator or super user to perform this command. Parameters: cmd argument is one of following control commands:  SHM_LOCK: Lock the specified shared memory segment.  SHM_UNLOCK: Unlock the shared memory segment.  IPC_STAT: Return the status information contained in the control structure and place it in the buffer pointed to by buf.  IPC_SET: Set the effective user and group identification and access permissions.  IPC_RMID: Remove the shared memory segment. Shared Memory Settings
  • 27.  The buf is a pointer to a type structure, struct shmid_ds which is defined in < sys/shm.h > struct shmid_ds { struct ipc_perm shm_perm; /* permissions */ size_t shm_segsz; /* size of segment in bytes */ pid_t shm_lpid; /* pid of last shmop() */ pid_t shm_cpid; /* pid of creator */ shmatt_t shm_nattch; /* number of current attaches */ time_t shm_atime; /* last-attach time */ time_t shm_dtime; /* last-detach time */ time_t shm_ctime; /* last-change time */ . . }; Shared Memory Settings
  • 28.  shmat() and shmdt() are used to attach and detach shared memory segments. They are prototypes as follows: void *shmat(int shmid, const void *shmaddr, int shmflg); int shmdt(const void *shmaddr);  shmat() returns a pointer, shmaddr, to the head of the shared segment associated with a valid shmid.  shmdt() detaches the shared memory segment located at the address indicated by shmaddr. Attaching and detaching a Shared Memory
  • 29. #include <stdio.h> #include <time.h> // for ctime() #include <sys/shm.h> #include <errno.h> int main(){ key_t key = 1234; // key to be passed to shmget() size_t size = 4096; // size of shared memory int shmflag = 0666 | IPC_CREAT; // read and write permission, // create shared memory if not exist int shmid; // return value from shmget() int ret; // return value from shmctl() struct shmid_ds shmds; // structure to store information // about shared memory // Create the shared memory segment using key 1234 shmid = shmget( key, size, shmflag ); Showing Status of a Shared Memory shm_status.c
  • 30. if ( shmid >= 0 ) { ret = shmctl( shmid, IPC_STAT, &shmds ); if (ret == 0) { printf( "Size of memory segment is %ldn", shmds.shm_segsz); printf( "Number of attaches %ldn", shmds.shm_nattch ); printf( "Access permissions %on", shmds.shm_perm.mode ); printf( "Create time %ld n", shmds.shm_ctime); printf( "Create time %s n", ctime(&shmds.shm_ctime)); } else { printf( "shmctl failed (%d)n", errno ); } } else { printf( "Shared memory segment not found.n" ); } return 0; } Showing Status of a Shared Memory shm_status.c
  • 31. #include <stdio.h> #include <sys/shm.h> #include <errno.h> #include <time.h> int main(){ int shmid, ret; struct shmid_ds shmds; shmid = shmget( 1234, 0, 0 ); if ( shmid >= 0 ) { ret = shmctl( shmid, IPC_STAT, &shmds ); if (ret == 0) { printf("old permissions were %on", shmds.shm_perm.mode ); shmds.shm_perm.mode = 0444; ret = shmctl( shmid, IPC_SET, &shmds ); ret = shmctl( shmid, IPC_STAT, &shmds ); printf("new permissions are %on", shmds.shm_perm.mode ); ret = shmctl( shmid, SHM_LOCK, 0 ); ret = shmctl( shmid, SHM_UNLOCK, 0 ); } Changing Permission of a Shared Memory shm_perm.c
  • 32. else { printf( "shmctl failed (%d)n", errno ); } } else { printf( "Shared memory segment not found.n" ); } return 0; } Changing Permission of a Shared Memory shm_perm.c
  • 33. #include <stdio.h> #include <sys/shm.h> #include <errno.h> int main(){ int shmid, ret; void *mem; // Get the shared memory segment using 1234 shmid = shmget(1234, 0, 0 ); if ( shmid >= 0 ) { mem = shmat( shmid, (const void *)0, 0 ); if ( mem > 0 ) { printf( "Shared Memory starting address is %pn", mem ); ret = shmdt(mem); if(ret == 0){ printf("Successfully detached memoryn"); } else { printf("Memory detached Failed (%d)n", errno); } } } } Detaching from a Shared Memory shm_detach.c
  • 34. #include <stdio.h> #include <sys/shm.h> #include <string.h> int main(){ int shmid, ret; void *mem; shmid = shmget( 1234, 4096, 0666 | IPC_CREAT ); // Attach to Shared Mamory mem = shmat( shmid, (const void *)0, 0 ); // Write to Shared Memory strcpy( (char *)mem, "This is a test string.n" ); printf( "%s", (char *)mem ); // Read from Shared Memory // Detach from Shared Mamory ret = shmdt( mem ); return 0; } Writing and Reading from a Shared Memory shm_rw.c
  • 35. #include <stdio.h> #include <sys/shm.h> #include <errno.h> int main(){ int shmid, ret; shmid = shmget( 1234, 0, 0 ); if ( shmid >= 0 ) { ret = shmctl( shmid, IPC_RMID, 0 ); if (ret == 0) { printf( "Shared memory segment removedn" ); } else { printf( "shmctl failed (%d)n", errno ); } } else { printf( "Shared memory segment not found.n" ); } return 0; } Removing a Shared Memory shm_rm.c
  • 36. Introduction to Semaphores  Semaphores are used to avoid race condition. Therefore, Semaphores are control mechanism.  Race condition occurs when two or more processes are in their critical section.  Critical section is a part of code in which a process accesses a shared resource.  So whenever two or more processes in their critical sections, their may be chances that they might go in race condition.  A semaphore is a data structure, which can be shared by a group of processes.  When several processes compete for same resource (e.g. a file, a message queue, or a shared memory), their operations may be synchronized with the use of semaphores, so that they do not interfere with each other. Semaphores
  • 37.  Semaphores ensure that only one process will be granted exclusive access of a particular resource.  All other processes requiring the same resource will be suspended by Linux kernel.  Once a process releases the resource, the kernel will grant exclusive access of the resource to a suspended process.  Semaphores are often used in pair in order to lock (protect) a resource and to subsequently unlock (release) a resource. Semaphores
  • 38.  Controlling the synchronization using an abstract data type called a semaphore was proposes by by Dijksta in1965.  A Semaphore S is a an integer variable that can be accesses only through two atomic operations. i.e. these operation can not be interrupted and can be treated as an indivisible step. Operation Semaphore Dutch Meaning Wait P proberen to test Signal V verhogen to increment Semaphores wait(S) { while (S<=0); S--; } signal (S) { S++; }
  • 39.  At its simplest a semaphore is variable S which takes one of two values:  0 when a resource is locked (protected), and should not be accessed by other processes  1 when the resource is unlocked (released).  Such semaphore, which could take two values 0 or 1, is called binary semaphore.  But in Linux implementation the two values are  –1, which is our P operation to wait for a semaphore to become available  +1, which is our V operation to signal that a semaphore is now available. Semaphores
  • 40.  As we know that a semaphore is a variable, so before performing any operation on semaphore it must exist. The semget call creates a set of semaphore along with its associated data structure (or gets an existing semaphore ) It is prototyped by: #include <sys/sem.h> #include <sys/ipc.h> #include <sys/types.h> int semget(key_t key, int nsems, int semflg); When the call succeeds, it returns the semaphore ID (semid). otherwise it returns –1, if call fails. Creating a new semaphores
  • 41. Parameters  key: is a access value associated with the semaphore ID.  nsems: the number of semaphores required (since UNIX provides an array of individual semaphores, to give control of multiple resources).  Setting it 1, means create one semaphore in a set.  semflg: specifies the initial access permissions and creation control flags.  This will be zero if the semaphore already exists  If not it should be like IPC_CREAT | 0666  Please Note, the initial value of a semaphore is zero when it is created first time. Creating a new semaphores
  • 42. #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <unistd.h> #include <errno.h> #include <stdio.h> int main(){ key_t key = 1234; // key to pass to semget() int semflg = 0666 | IPC_CREAT; // semflg to pass to semget() int nsems = 1; // nsems to pass to semget() int semid; //return value from semget() if((semid = semget(key, nsems, semflg)) ==-1){ perror("semget: semget failed"); exit(-1); } printf( "semget Created a semaphore with id = %d n", semid ); return 0; } Removing a Shared Memory sem_create.c
  • 43. Controlling Semaphores  Function semctl() changes permissions and other characteristics of a semaphore set. It's prototype is as followed: int semctl(int semid,int semnum,int cmd, union semun sem_union);  It returns different values depending on the cmd.  For setting the value of a single semaphore or removing the semaphore set, it returns 0 on success, -1 for failure. Parameters:  semctl must be called with a valid semaphore ID, semid.  The semnum value selects a semaphore within an array by its index.  To access first semaphore its values is 0. Creating a new semaphores
  • 44.  All the control operations on the set of semaphores, which are identified by semaphores ID semid are specified by third the argument cmd.  The parameters cmd can take the values are given by:  GETVAL: Returns the semaphore’s value.  SETVAL: Set the semaphore value given in sem_union  GETPID: Get PID of the process that last called semop.  IPC_STAT: Return the effective user, group, and permission for a semaphore in sem_union.  IPC_RMID: Remove the specified semaphore set with semid along with its associated data structure.  If the semctl call fails, it returns –1, otherwise it returns an integer value of depending on the value of cmd. Creating a new semaphores
  • 45. #include <stdio.h> #include <sys/sem.h> #include <stdlib.h> int main(){ int semid, cnt; semid = semget( 1234, 1, 0 ); // Get the semaphore with the key 1234 if (semid >= 0) { // Read the current semaphore count. Index of semaphore is // 0. The command is GETVAL. The return value from this // command is either –1 for error or the count of the // semaphore. cnt = semctl( semid, 0, GETVAL ); if (cnt != -1) { printf("semcrd: current semaphore count %d.n", cnt); } } return 0; } Semaphore: Get Current Count sem_getval.c
  • 46. // Setting the Current Semaphore Count #include <stdio.h> #include <sys/sem.h> #include <stdlib.h> int main(){ int semid, ret; /* Get the semaphore with the key 1234 */ semid = semget( 1234, 1, 0 ); if (semid >= 0) { // Set the semaphore No.0 to a value 6, changing the binary // semaphore to a counting semaphore ret = semctl( semid, 0, SETVAL, 6); if (ret != -1) { printf("current semaphore count updated n"); } } return 0; } Semaphore: Set Count sem_setval.c
  • 47. #include <stdio.h> #include <sys/sem.h> #include <stdlib.h> int main() { int semid, ret; /* Get the semaphore with the key 1234 */ semid = semget( 1234, 1, 0 ); if (semid >= 0) { /* Remove Semaphore having id semid */ ret = semctl( semid, 0, IPC_RMID); if (ret != -1) { printf("Semaphore %d removed.n", semid ); } } return 0; } Removing a Semaphore sem_rm.c
  • 48.  The semop() API function provides the means to acquire and release a semaphore or semaphore array.  The basic operations provided by semop are  Decrement semaphore (to acquire semaphores)  Increment a semaphore (to release semaphores). It is prototyped by: int semop(int semid , struct sembuf *sops , unsigned int nsops); Parameters:  semid: the semaphore ID returned by semget() call.  sops: is a pointer to an array of structures, each containing the following information about a semaphore operation: Semaphore Operations
  • 49.  The semaphore number of interest sem_num, usually 0 means first semaphore from an array.  The operation to be performed sem_op, is the value by which the semaphore should be changed. (You can change a semaphore by amounts other than 1.) In general, only two values are used,  –1, which is your P operation to wait for a semaphore to become available  +1, which is your V operation to signal that a semaphore is now available.  a flags word sem_flg can be used to alter the behavior of the operation. usually set to SEM_UNDO means if the process terminates without releasing the semaphore, allows the operating system to automatically release the semaphore. Semaphore Operations
  • 50.  The sembuf structure is shown below: struct sembuf { unsigned short sem_num; short sem_op; short sem_flg; };  nsops: Number of semaphores in the array Semaphore Operations
  • 51. #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <unistd.h> #include <errno.h> #include <stdio.h> int main() { int semid; struct sembuf sb; semid = semget( 1234, 1, 0 ); if (semid >= 0){ /* build semaphore operations structure */ sb.sem_num = 0; /*semaphore number,0 for first semaphore */ sb.sem_op = -1; /* operation -1 means acquire semaphore */ sb.sem_flg = 0; /* operation flags*/ printf( "Attempting to acquire semaphore %dn", semid ); if ( semop( semid, &sb, 1 ) == -1 ) { /* if the value of a semaphore is 0 this will wait until it becomes > 0 */ printf( "semacq: semop failed.n" ); exit(-1); } printf( "semacq: Semaphore acquired %dn", semid ); } return 0; } Getting a Semaphore sem_acquire.c
  • 52. #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <unistd.h> #include <errno.h> #include <stdio.h> int main() { int semid; struct sembuf sb; semid = semget( 1234, 1, 0 ); if (semid >= 0){ /* build semaphore operations structure */ sb.sem_num = 0; /*semaphore number,0 for first semaphore */ sb.sem_op = 1; /* operation +1 means release semaphore */ sb.sem_flg = 0; /* operation flags*/ printf( "Releasing a semaphore %dn", semid ); if ( semop( semid, &sb, 1 ) == -1 ){ printf( "semacq: semop failed.n" ); exit(-1); } printf( "semacq: Semaphore released %dn", semid ); } return 0; } Releasing a Semaphore sem_release.c
  • 53. Examples /* waiting P(sv): */ static int semaphore_p(void){ struct sembuf sem_b; sem_b.sem_num = 0; /* first semaphore */ sem_b.sem_op =-1; /*P(sv)*/ sem_b.sem_flg =0; if(semop(semid, &sem_b , 1 ) == -1){ perror("semop: semop failed"); return(0); } return(1); } Semaphore Operations
  • 54. Examples /* giving controll V(sv) */ static int semaphore_v(void){ struct sembuf sem_b; sem_b.sem_num = 0; /* first semaphore */ sem_b.sem_op = 1; /*V(sv)*/ sem_b.sem_flg =0; if(semop(semid, &sem_b, 1) == -1){ perror("semop: semop failed"); return(0); } return(1); } Semaphore Operations
  • 55. Examples /* giving controll V(sv) */ static int semaphore_v(void){ struct sembuf sem_b; sem_b.sem_num = 0; /* first semaphore */ sem_b.sem_op = 1; /*V(sv)*/ sem_b.sem_flg =0; if(semop(semid, &sem_b, 1) == -1){ perror("semop: semop failed"); return(0); } return(1); } Semaphore Operations
  • 56. Q 1. Write a client Server application in C using message queues in which the client takes an integer from the user and sends this integer to the server through message queue, for computation of its factorial. The client program should return message queue ID, so that you could use this ID when you run the server. Q 2. Write a client Server application in C using message queues in which the client takes Linux command from the user and sends this command to the server through message queue, for execution of Linux command. The server takes that command through message queue and executes this command. Assignment Topic: Message Queues
  • 57. Q 3. Write Client and Server programs in C using the concept of shared memory. If for example, the client program writes an integer n in the shared memory, server reads this integer n from the shared memory, and prints this integer n number of time. The server program should be terminated if it reads a negative integer from the shared memory. Q 4. Write a Client & Server program in C using the concept of shared memory. The server creates a shared memory segment to store its process ID. The client reads process ID of the server. Using server process ID, the client program can raise signals SIGINT, SIGTSTP, SIGQUIT (by using kill() system call), in such a way that when a user presses:  i or I it raises signal SIGINT  z or Z it raises signal SIGTSTP  q or Q it raises SIGQUIT  Error message if user presses any other character. The server program should provide handlers for catching above signals. The server ignores signals on receiving SIGINT, or SIGTSTP (use SIG_IGN for ignoring the signal). However, the server program quits on receiving SIGQUIT. The client program also quits after sending SIGQUIT signal. Assignment Topic: Shared Memory
  • 58. Q 5. Write a C-program, in which 1. first create an integer type of shared memory segment, 2. Then lock this segment through Semaphore, so that other processes cannot access it. 3. it writes a number in this shared segment. 4. Then unlock this segment through Semaphore so that other processes can access it. Q 6. Write another C-program, in which 1. locks this segment through Semaphore first 2. Reads integer from shared memory 3. Unlocks semaphore 4. Prints integer on screen Assignment