32
Real Time System KUKUM Module #3 POSIX programming- Shm Lecture 4

KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Embed Size (px)

Citation preview

Page 1: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Module #3POSIX programming- Shm

Lecture 4

Page 2: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Unix Interprocess Comm

• Unix is rich in inter process communication mechanism. These are:

• Signal• Pipe• FIFO (named pipe)• IPC

– Message queues– Semaphore– Shared memory (fastest)

Page 3: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

IPC• An elegant means of interprocess communication mechanisms

provided by the group of techniques called IPC IPCs are also directly managed by kernel

• Using IPCs, concurrent processes can interact in a client-server manner (eg: database server) or peer-to-peer manner( eg: email server)

• Within a machine each of these resources is identified by an integer called “KEY”, ie the key is used as the sharing anchor.

• Each resource belongs to an owner and has access rights

• There are two shell commands to check on them:– ipcs (similar to ls) –list down all the IPC resources currently available– Ipcrm (similar to rm) – remove the IPC resource given as argument in

the command

Page 4: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

ipcs command[staff@localhost staff]$ ipcs

-------Shared Memory segments---------Key shmid owner perms bytes nattch status0x0000 163841 staff 600 339216 2 dest0x0000 196610 staff 600 393216 2 dest

……Semaphore Arraya……………….Key semid owner perms nsems

…….message queues--------------------Key msqid owner perms used-bytes messages

Page 5: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

IPC mechanisms <ipc.h>• Messages - a tech. which allows processes on

the same machine to exchange formatted message

• Semaphore – a set of wide variables which can be modified and used by processes on the same machine to synch execution.

• Shared memory - a common region of virtual memory( part of RAM), shared by multiple processes on the same machine, such that the data in the shared memory can be directly read and modified by other processes

Page 6: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

IPC generic operations

• All three IPCs share a set of generic operations:– get operation : to create or gain access to

resource. The sys call returns a facility identifier to be used in calls to other IPC routines,

– Control oper: to get status or set ctrl values– Specific oper: to do more specific task based

on the type of resource.

Page 7: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Common data structure• Note the common definitions for constants

across these mechanisms used in their respective sys calls.

• The values of IPC_CREAT and others like it are defined in <sys/ipc.h>

• #define IPC_CREAT 0x1000• #define IPC_EXCL 0x2000

– These constant are usually bit-wise operated, eg: IPC_CREAT | “0600” is bitwise OR-ed to achieve the required access rights

Page 8: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Unix Interprocess Comm

• Unix is rich in inter process communication mechanism. These are:

• Signal• Pipe• FIFO (named pipe)• IPC

– Message queues– Semaphore– Shared memory (fastest)

Page 9: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Shared Memory ( shm)

• The fastest form of inter- process communication involving data

Process 1 Process 2

memory

Shared Region

Page 10: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

…/ shm• The shm (segment) can be shared by many

processes, and a process may access many shared segments

• Semaphore/messages are used by the kernel to manage write/read to the segment

• When a shm is identified, it is initially outside the address space of a process. The process has to execute sys calls to include it into the space

Page 11: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

…/shm

• System calls involved are:– shmgetshmget to translate a shm KEY to a segment-

ID.– shmatshmat to amap/attach a segment to the

process address space– shmdtshmdt to detach a segment from the process

address space.– shmctlshmctl to destroy a segment when it is no

longer required.

Page 12: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Shm-reader process#include <stdio.h>#include “sys/ipc.h”#include “sys/shm.h”#define KEY 1000 /* key for the shm */

main(){ int descr, *p, i;

printf((“shm: Start of main of “ readerprocess…\n”);//request shared memory of size 10 x integer sizedescr= shmget(KEY,10*sizeof(int), IPC_CREAT|0660);p = (int *)shmat(descr, NULL,0);

while(1){ sleep(2);for(i=0; i<10; i++) { printf(“shm: value of p[%d]= %d\n”,I,p[i]); }

}}

Page 13: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Shm –writer process#include <stdio.h>#include “sys/ipc.h”#include “sys/shm.h”#define KEY 1000 /* key for the shm */

main(){ int descr, i,g ; int *p;

printf((“shm: Start of main of “ writer process…\n”);

//request shared memory of size 10 x integer sizedescr= shmget(KEY,10*sizeof ( int ), IPC_CREAT|0660);p = (int *)shmat(descr, NULL,0);g=0;

while(1){ sleep(1);for(i=0; i<10; i++) { p[i] =g; g=g+1;}

}}

Page 14: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Output

• It’s time to think

• Explain how does the code behave??

Page 15: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Exercise

1. Modify the program so that you can accommodate a different data strucuture for the shared memory region, fro example which consist of:

An array of integers of size 10, followed by an array of characters of size 20 and followed by an array of double of size 5.

Page 16: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

UNIX IPC mechanism

• Unix is rich in inter process communication mechanism. These are:

• Signal• Pipe• FIFO (named pipe)• IPC

– Message queues– Semaphore– Shared memory (fastest)

Page 17: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Concept of ‘messages’• Allow sending and receiving of messages among

multiple processes, analogy: having a central mailbox in a building where many people can deposit and receive mailsfromthe box.

• Just like all messges have receipient address, each message has an integer mesae type assigned by the sender, so tht receipient process can selectively recive messages based on the type.

• Messages stored in queue are permanent, even when no proces is referencing the queue. A message is remove only when a process explicitly removes it from the queue.

• There can be many message queues, which are referred and used by many processes, and this reflects the dynamism for interprocess comm using this technique.

Page 18: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Problems with pipe and FIFO

• No mechanism for selective communication between processes, eg: A,B are writers, C, D are readers to a pipe. If A’s data is only meant for C and B’s data for D, then C an D cannot selectively read data relevant to each o them only.

• With the un-named pipe, problem of transience ( exist only temporarily) is also true.

Page 19: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Kernel data structure for message queue

Message table

msg3 msg1msg2

record

Page 20: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Sending and Retrieving messages

• When a process sends a message to the queue, the kernel creates a new message record and puts it at the end of the list.

• When process retrieve a message, the kernel copies the content to his virtual address, then discard the message from the queue. Retrieval can be:

– Retrieval the oldest regardless of message type– Retrieve the message with ID matches the one requested by the

process. If there are many take the oldest.– Retrieve a message whose type is lowest among those which

are less than or equal.

Page 21: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

…/Sending and retrieving messages

• If there is no message to be read which satisfies the retrieval criteria, the process will be blocked, unless specified otherwise( IPC_NOWAIT flag is set, and returns a failure).

• There are also system imposed limits on manipulation of messages ,eg: MSGMNI = max no. of queues that can exist, MSGMAX = max size of a message etc.

• Any system call that attempts to trangress these limits will fail.

Page 22: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Message APIs• msgget – open and create if needed, a message

queue for acces• msgsend – send a message toamessage queue• Msgrcv – retrieve a message• Msgctrl – manipulate the control data of a

message queue

• These are analogous to : open, read, write,stat,unlink, chmod etc for files

Page 23: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Message queue program – q.h/* q.h– header for message facility example*/#include <stdio.h>#include <errno.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>

extern int errno;

#define QKEY(key_t)0105 /*identifying key for queue*/#define QPERM 0660 /*permission bits for queue*/#define MAXOBN 50 /*max len of object name*/#define MAXPRIOR 10 /*max priority level*/

struct q_entry{ /*structure used for message*/long mtype;char mtext[MAXOBN+1];

};

Page 24: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Message queue prog- init_queue (create queue)

/*init_queue – get queue identifier */#include “q.h”

init_queue(){

int queue_id;/* attempt to create message queue */if((queue_id = msgge(QKEY, IPC_CREAT|QPERM)==-1)

perror(“init_queue: msggetfaied”);

return queue_id;}

Page 25: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Message queue program – client.c

/*enter – places an object into a queue*/#include “q.h”static int s_qid = -1; /*message queue identifier*/char *objname; /*objname*/int priority; /* priority level */{

int len;char *strncpy();

strcut q_entry s_entry; /* strcut to hold msg */

/* 1st validate length and priority level */

if((len =strlen(objname))>MAXOBN){printf(“name too lon \n”);

return(-1);}

Page 26: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

…/ client

if(priorit >MAXPRIOR || priority<0){printf(“client:invalid priority\n”);return(-1);

}If(s_qid== -1 && ( s_qid = init_queue())==-1)

return(-1);

/*initialize s_entry*/s_entry.mtype=(long)priority;strncpy(s_entry.mtext,objname, MAXOBN);

/*send message, wait if necessary */if(msgsnd(s_qid,&s_entry,len,0)==-1){

perror(“client: msgsnd failed”);return(-1);}

elsereturn(0);

}

Page 27: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Message queue program- server.c/* server – server object with highest priority on queue */#include “q.h”

static int r_qid = -1;/*msg queue identifier*/serve(){

int mlen;struct q_entry, r_entry;/*strcut to hldmsg */

/*initialize queue */if(r_qid== -1 && ( r_qid = init_queue()) ==-1)

return(-1);for(;;){if(mlen=msgrcv(r_qid, &r_entry, MAXOBN,(long)-1*MAXPRIOR, MSG_NOERROR)) == -1){

perror(“msgrcv failed”);return(-1);

}else{/*make sure we have string */

r_entry.mtext[mlem] =‘\0’;

/*process object name */proc_obj(&r_ntry);}

}}

Page 28: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Test Program- client_test.c/* client_test- client enters object name into a queue*/#include <stdio.h>#include “q.h”

main(argc, argv){

int argc; char *argv[];int priority;

if(argc != 3){fprintf(stderr, “usage: %s objnme priority\n”,argv[0]);exit(1);}

if((priority=atoi(argv[2]))<=0 || priority > MXPRIOR){printf(“Invalid priority \n”);exit(2);}

if(enter(argv[1],priority)<0){printf(“enter fails\n”);exit(3);}

exit(0);}

Page 29: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Test prog- server_test.c/* server_test –simple server for queue*/#include <stdio.h>#include “q.h”

main(){

int pid;pid=fok();switch(pid){

case 0: //childsetpgrp(); //break link with teminal, i.e with

parent //and become a new proces leaderprintf(“Sever pocess pid is %d \n”,getpgrp());serve();break; //in real serve never exits

Page 30: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

…/ server_test.ccase -1: printf(“fork to start seve failed \n”);

break;default:

;}exit(pid != -1 ? 0:1); // not good in SE

proc_obj(msg);struct q_entry *msg;{

printf(“\npriority: %ld name:%s\n”, msg->mtype, msg->mtext);

}

Page 31: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

Execution outputpower0:12/user/test>client_test kerja1 3power0:13/user/test>client_test kerja2 5power0:14/user/test>client_test kerja3 8power0:15/user/test>client_test kerja4 1

power0:20/user/test>server_testserver process pid is 27238priority: 1 name: kerja4priority: 2 name: kerja1priority: 3 name: kerja2priority: 3 name: kerja3

Page 32: KUKUM Real Time System Module #3 POSIX programming- Shm Lecture 4

Real Time System KUKUM

The END