Linux12 January 2010Knowx innovation1
UnixDeveloped at Bell Labs in late 1960sOwned by AT&T at the time, which meant you had to buy it once AT&T figured out it was valuableWritten in C (a high level language)Needs to be compiled to runCan be easily moved to a different system by re-compiling for new hardware12 January 2010Knowx innovation2
Why LinuxEntire OS source code is freeFull freedom to study, modify, redistribute. No payments or restrictions.Kernel and many packages follow GNU GPL, LGPL or BSD style license.Powerful command line (shells)Multitasking, SMP, NUMA12 January 2010Knowx innovation3
Protected memoryTrue multiuser capabilitiesFilesystem choices:ext3, JFS, XFS, reiserFSHighly modular & scalable: From embedded systems to IBM mainframes 12 January 2010Knowx innovation4
distributionDebian (related: Knoppix, (k)ubuntu, Mepis, Xandros)
RedHat (related: Fedora, CentOS)
SUSE (related: OpenSUSE)
Mandriva
Slackware
Embedded Linuxes12 January 2010Knowx innovation5
GNU/Linux architecture12 January 2010Knowx innovation6
Linux kernelMediates access to the hardware and peripheralsShells Provides user access to the kernelApplications Provide the useful function for the operating system12 January 2010Knowx innovation7
Kernel architecture12 January 2010Knowx innovation8
Gnu compiler collection(gcc)Compiler and set of utilities to build binaries from high level source code.Standard for embedded systems developmentSince its supports so many different target architecturesSupports a number of languagesC, C++, ada, java, FORTRAN, Pascal12 January 2010Knowx innovation9
Stage of compilation12 January 2010Knowx innovation10
12 January 2010Knowx innovation11
makefile12 January 2010Knowx innovation12
make utility uses a developer-created input file to describe the project builtGNU uses the name Makefile as the default name for its input file.12 January 2010Knowx innovation13
appexp : main.o app.o bar.o lib.o	gcc –o appexp main.o app.o bar.o lib.omain.o : main.c lib.h app.h	gcc –c -o main.o main.capp.o: app.c lib.h app.h	gcc –c -o app.o app.cbar.o : bar.c lib.h	gcc –c -o bar.o bar.clib.o : lib.c lib.h	gcc –c -o lib.o lib.cLine 1: is the ruleThe portion of the rule  before the colon is called  targetand after the colon is called  dependencies.12 January 2010Knowx innovation14
File handlingAccomplished through the standard C libraryWe can create and manipulate ASCII text or binary files with the same API.APIfopen, fclose, fwrite , fread, fseek, and rewind.12 January 2010Knowx innovation15
fopen Opening a file can also be the mechanism to create a fileprototype:FILE * fopen(const char *filename,const char *mode)filename - file we wish to access or createmode – mode we wish to useFILE * - fopen returns the FILE pointer (FILE *) 12 January 2010Knowx innovation16
ExampleFILE *fin; fin = fopen("inpfile.txt", "r"); 12 January 2010Knowx innovation17
Program#include <stdio.h> #define MYFILE "missing.txt" main() {FILE *fin;	 	fin = fopen( MYFILE, "r" );	/* Try to open the file for read */  	if (fin == (FILE *)0) 	/* Check for failure to open */ 	{printf(“error in opening file”); /* Emit an error message and exit */exit(-1);} 	fclose( fin ); /* All was well, close the file */ }12 January 2010Knowx innovation18
fread()  and  fwrite()Prototypes:size_t fread(void *ptr, size_t size, size_t nmemb,FILE *stream);size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);fseek()Prototype:int fseek (FILE * stream, long offset, int whence);Function allows to the new position given an indexwhence argument defines 12 January 2010Knowx innovation19
SEEK_SET   -   moves the file position to the position defined by 			offsetSEEK_CUR  -moves the file position the number of bytes defined 			by offset from the current file positionSEEK_END -     moves the file position to the number of bytes defined by 		offset from the end of the filerewind ()Resets the file read pointer back to the start of the filePrototypevoid rewind (FILE * stream);12 January 2010Knowx innovation20
Program#include <stdio.h>#define MAX_LINE 40 #define FILENAME "myfile.txt“typedef struct { int id; float x_coord; float y_coord; char name[MAX_LINE+1]; }MY_TYPE_T; MY_TYPE_T object;int main() {int i;FILE *fin; fin = fopen( FILENAME, "r" );	 /* Open the input file */12 January 2010Knowx innovation21
 if (fin == (FILE *)0) 	exit(-1);fseek( fin, (2 * sizeof(MY_TYPE_T)), SEEK_SET ); /* Get the last entry */fread( &object, sizeof(MY_TYPE_T), 1, fin ); printf("%d %f %f %s\n", object.id, object.x_coord, object.y_coord, 	object.name );rewind( fin );	 /* Get the second to last entry */ fseek( fin, (1 * sizeof(MY_TYPE_T)), SEEK_SET );fread( &object, sizeof(MY_TYPE_T), 1, fin );printf("%d %f %f %s\n", object.id, object.x_coord, object.y_coord, 	object.name ); 12 January 2010Knowx innovation22
/* Get the first entry */rewind( fin ); fread( &object, sizeof(MY_TYPE_T), 1, fin ); printf("%d %f %f %s\n", object.id, object.x_coord, object.y_coord, 	object.name ); fclose( fin );return 0; }  12 January 2010Knowx innovation23
getpid()    - to get the current process ID.getppid()  - to get the parent process ID.getuid()    - to get the user ID.getgid()    - to get the group ID.12 January 2010Knowx innovation24
Program#include <stdio.h> #include <unistd.h> #include <sys/types.h> int main(){pid_t myPid; pid_t myParentPid; gid_t myGid; uid_t myUid; myPid = getpid(); myParentPid = getppid(); myGid = getgid();12 January 2010Knowx innovation25
myUid = getuid(); 	printf( "my process id is %d\n", myPid ); 	printf( "my parent's process id is %d\n", myParentPid );printf( "my group id is %d\n", myGid );printf( "my user id is %d\n", myUid ); return 0; } Outputmy process id is 10932.my parents process id is 10795My group id is 500My user id is 50012 January 2010Knowx innovation26
Process apiForkCreate a new child processWaitSuspend execution until a child processes exitsSignalInstall a new signal handlerExecReplace the current process image with a new process image12 January 2010Knowx innovation27
ForkCreating new processes with in a given process.return value of fork is greater than zero then in the parent context.	Equal to zero then in the child context.less than zero then error occurred.12 January 2010Knowx innovation28
Examplepid_t pid;pid = fork();if(pid>0)	{/*parent context*/}else if (pid ==0)	{/*child context*/}else{/*error occurred no child created*/}12 January 2010Knowx innovation29
12 January 2010Knowx innovation30
Program#include <sys/types.h> #include <sys/wait.h> #include <unistd.h>#include <stdio.h> #include <errno.h> int main() {pid_t ret; int status, I, role = -1;12 January 2010Knowx innovation31
ret = fork(); if (ret > 0) { 	printf("Parent: This is the parent process (pid %d)\n", 	getpid()); 	for (i = 0 ; i < 6 ; i++) 	{   printf("Parent: At count %d\n", i); sleep(1); }	   ret = wait( &status ); 	   role = 0; 	}else if (ret == 0)	{   printf("Child: This is the child process (pid %d)\n", getpid()); 12 January 2010Knowx innovation32
	for (i = 0 ; i < 6 ; i++) 	{printf("Child: At count %d\n", i); 	sleep(1); } role = 1;	 }else 	{ 	   printf("Parent: Error trying to fork() (%d)\n", errno); 	}printf("%s: Exiting...\n", ((role == 0) ? "Parent" : "Child")); return 0; } 12 January 2010Knowx innovation33
waitSuspend the calling process until a child process(created by this process) exits or until a signal is delivered.Prototypepid_t wait (int *status);12 January 2010Knowx innovation34
SignalInstall a signal handler for a process.Prototypesighandler_t signal (int signum, sighandler_t handler);SIGHUP  - hang up –commonly used to restart a task.SIGKILL - kill signalSIGINT   - interrupt from the keyboardSIGSTOP – stop processSIGQUIT – quit signal from keyboard12 January 2010Knowx innovation35
Program#include <stdio.h> #include <sys/types.h>#include <sys/wait.h>#include <unistd.h> #include <signal.h>#include <errno.h> void usr1_handler( int sig_num ) { 	printf( "Process (%d) got the SIGUSR1\n", getpid() ); }int main() { pid_t ret;int status role = -1; signal( SIGUSR1, usr1_handler ); 12 January 2010Knowx innovation36
ret = fork();if (ret > 0) {	 /* Parent Context */printf( "Parent: This is the parent process (pid %d)\n", getpid() ); role = 0; pause(); printf( "Parent: Awaiting child exit\n" );ret = wait( &status );}12 January 2010Knowx innovation37
else if (ret == 0) { /* Child Context */ printf( "Child: This is the child process (pid %d)\n", getpid() );role = 1; pause(); } else { /* Parent Context -- Error */ printf( "Parent: Error trying to fork() (%d)\n", errno ); }printf( "%s: Exiting...\n", ((role == 0) ? "Parent" : "Child") ); return 0;} 12 January 2010Knowx innovation38
execReplaces the current process image altogether.Once the exec function replaces the current process, its pid is the same as the creating processPermits the current process context to be replace with the program specifies as the first argument.12 January 2010Knowx innovation39
Example	execl(“/bin/ls”,”ls”,”-la”,null);This command replaces the current process with the ls (list directory)Prototypes for the variants of execint execl (const char *path,const char * arg, …,..)int execlp(const char *path,const char *arg,……)int execv(const char *path, char *const argv[])int execvp(const char *file, char *const argv[])12 January 2010Knowx innovation40
Program for shell interpreter#include <sys/types.h> #include <sys/wait.h>#include <unistd.h>#include <stdio.h>#include <stdlib.h> #include <string.h> #define MAX_LINE 80 int main() {int status; pid_t childpid;char cmd[MAX_LINE+1]; char *sret;12 January 2010Knowx innovation41
 while (1) {printf("mysh>"); sret = fgets( cmd, sizeof(cmd), stdin ); if (sret == NULL) exit(-1);cmd[ strlen(cmd)-1] = 0; if (!strncmp(cmd, "bye", 3)) exit(0);childpid = fork(); if (childpid == 0)	{ execlp( cmd, cmd, 0 ); }else if (childpid > 0) 	{ waitpid( childpid, &status, 0 ); } printf("\n"); } return 0;} 12 January 2010Knowx innovation42
Message queuesMessages are small collections of data (400 bytes, for example) that can be passed between cooperating programs through a message queue.Messages within a queue can be of different types, and any process with proper permissions can receive the messages.12 January 2010Knowx innovation43
Creating message queue APImsgget(key_k key , int msgflg)the key which signifies the name given to the queueflags argument must contain the permission bits for the new queueIPC_CREAT if the queue is being createdIPC_EXCL return an error if the message queue already existsReturn the msgidExample msgget(111 , 0666 | IPC_CREAT);12 January 2010Knowx innovation44
Program#include <stdio.h> #include <sys/msg.h>#define MY_MQ_ID 	111int main(){int msgid;/* Create the message queue with the id MY_MQ_ID */ msgid = msgget( MY_MQ_ID, 0666 | IPC_CREAT ); if (msgid >= 0) 	{ printf( "Created a Message Queue %d\n", msgid ); }return 0;} 12 January 2010Knowx innovation45
Sending the messageAPIint msgsnd (int msqid, const void *msgp, size_t msgsz, int msgflg); Takes 4 parametersmsqid is the queue id of the existing queue.msgp is the pointer that contains the address of the structure that holds the message and type.struct message{ long mtype; //The message type.prioritychar mesg [MSGSZ];//The message is of length MSGSZ. }; 12 January 2010Knowx innovation46
MSGSZ is the length of the message sent in bytes.MSGFLG specifies the action to be taken if one or more of the following are true.The number of bytes already in the queue is equal to msg_qbytes.The total number of messages on all queues on the system has reached a maximum limitAction to be takenIf (msgflg & IPC_NOWAIT) is non-zero, the message will not be sent and the calling process will return immediatelyIf (msgflg & IPC_NOWAIT) is 0, the calling process will suspend execution until one of the following occurs: 12 January 2010Knowx innovation47
Program#include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h>#include <stdio.h> #include <string.h> #define MSGSZ 128 typedef struct msgbuf   	/* will hold the message to be put in the queue */{ long mtype; 		/* priority of message */char mtext[MSGSZ];	/* the message that is stored */ }message_buf; main() { int msqid; int msgflg = IPC_CREAT | 0666; key_t key; message_buf sbuf; size_t buf_length; key = 10;printf("Calling msgget with key %#lx and flag %#o\n",key,msgflg);12 January 2010Knowx innovation48
/*A queue is created using the msget function with a key value 10 and the flag parameter being IPC_CREAT|06668 */ if ((msqid = msgget(key, msgflg )) < 0){ perror("msgget"); 	exit(1); } else printf("msgget: msgget succeeded: msqid = %d\n", msqid); sbuf.mtype = 1; 	/*setting the priority as 1 */printf("msgget: msgget succeeded: msqid = %d\n", msqid);(void) strcpy(sbuf.mtext, "I am in the queue?"); /* copy the text "I am in the queue" into the array mtext which is message array */printf("msgget: msgget succeeded: msqid = %d\n", msqid);12 January 2010Knowx innovation49
 buf_length = strlen(sbuf.mtext) + 1 ; /*sending the message with option IPC_NOWAIT */if (msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) < 0){ printf ("%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, 						buf_length); 	perror("msgsnd"); 	exit(1); } else printf("Message: \"%s\" Sent\n", sbuf.mtext); exit(0); }12 January 2010Knowx innovation50
Receive the messageAPIint msgrcv (int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);Arguments-msqid is the queue id of the existing queue.msgp is the point to a receiving buffer large enough to hold the received messagemsgszthe maximum size of the received message12 January 2010Knowx innovation51
program#include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #define MSGSZ 128 typedef struct msgbuf /* structure that will hold the message obtained 			from the queue*/{ 	long mtype; 	/*priority of message */	char mtext[MSGSZ];	/*message that stored */} message_buf;main() {12 January 2010Knowx innovation52
 int msqid; key_t key; message_buf rbuf; key = 10;/*creating a queue with the key value 10, */if ((msqid = msgget(key, 0666)) < 0){ perror("msgget"); exit(1); } /*acquires the message from the queue into rbuf*/if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0) < 0) 	{ perror("msgrcv");exit(1); }printf("%s\n", rbuf.mtext); exit(0); } 12 January 2010Knowx innovation53
Configuring message queueAPImsgctl(int msqid, int cmd, struct msqid_ds *buf)3 Arguments msqid is the queue id cmd is a command constant*bufis a pointer to structure.Use to get the info about a message queueSet the info for a message queueRemove a message queue12 January 2010Knowx innovation54
12 January 2010Knowx innovation55
Variable that is protected.It provides a means to restrict access to a resource that is shared amongst two or more processesTwo operations are permitted , called acquire and release.2 types of semaphore.Binary and Counting 12 January 2010Knowx innovation56Semaphore
The signal notationsP(semaphore variable) for waitV(semaphore variable) for signal12 January 2010Knowx innovation57
A binary semaphore is a variable that can take only the values 0 and 1.Represents a single resource and therefore when one process has acquired it,others are blocked until it is released.P(sv) if sv greater than 0 , decrement sv.ifsvis zero suspend execution of the processV(sv) if other process has been suspended waiting for sv, make it resume.if no waiting, increment sv12 January 2010Knowx innovation58Binary semaphore
12 January 2010Knowx innovation59
Represent shared resources in quantities greater than one.It could represent the entire set of buffers by setting its value to the number of buffers available.Whenever the process acquires the semaphore, the value decrement .When the semaphore value reaches zero, process are blocked until it becomes a non zero.12 January 2010Knowx innovation60Counting semaphore
12 January 2010Knowx innovation61
Creating semaphoreAPIsemget( key_t key, int num_sems, int sem_flags)Key is the semaphore keyNum_sems is the Semaphore countFlags To acquire or release of semaphoreAPIsemop(int sem_id, struct sembuf *sem_ops,size_tnum_sem_ops)12 January 2010Knowx innovation62
sem_id, is the semaphore identifier, as returned from semget.sem_ops, is a pointer to an array of structures, each of which will have at least the following members:Struct sembuf{short sem_num;short sem_op;short sem_flg;}12 January 2010Knowx innovation63

Linux

  • 1.
  • 2.
    UnixDeveloped at BellLabs in late 1960sOwned by AT&T at the time, which meant you had to buy it once AT&T figured out it was valuableWritten in C (a high level language)Needs to be compiled to runCan be easily moved to a different system by re-compiling for new hardware12 January 2010Knowx innovation2
  • 3.
    Why LinuxEntire OSsource code is freeFull freedom to study, modify, redistribute. No payments or restrictions.Kernel and many packages follow GNU GPL, LGPL or BSD style license.Powerful command line (shells)Multitasking, SMP, NUMA12 January 2010Knowx innovation3
  • 4.
    Protected memoryTrue multiusercapabilitiesFilesystem choices:ext3, JFS, XFS, reiserFSHighly modular & scalable: From embedded systems to IBM mainframes 12 January 2010Knowx innovation4
  • 5.
    distributionDebian (related: Knoppix,(k)ubuntu, Mepis, Xandros)
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
    Embedded Linuxes12 January2010Knowx innovation5
  • 11.
  • 12.
    Linux kernelMediates accessto the hardware and peripheralsShells Provides user access to the kernelApplications Provide the useful function for the operating system12 January 2010Knowx innovation7
  • 13.
    Kernel architecture12 January2010Knowx innovation8
  • 14.
    Gnu compiler collection(gcc)Compilerand set of utilities to build binaries from high level source code.Standard for embedded systems developmentSince its supports so many different target architecturesSupports a number of languagesC, C++, ada, java, FORTRAN, Pascal12 January 2010Knowx innovation9
  • 15.
    Stage of compilation12January 2010Knowx innovation10
  • 16.
  • 17.
  • 18.
    make utility usesa developer-created input file to describe the project builtGNU uses the name Makefile as the default name for its input file.12 January 2010Knowx innovation13
  • 19.
    appexp : main.oapp.o bar.o lib.o gcc –o appexp main.o app.o bar.o lib.omain.o : main.c lib.h app.h gcc –c -o main.o main.capp.o: app.c lib.h app.h gcc –c -o app.o app.cbar.o : bar.c lib.h gcc –c -o bar.o bar.clib.o : lib.c lib.h gcc –c -o lib.o lib.cLine 1: is the ruleThe portion of the rule before the colon is called targetand after the colon is called dependencies.12 January 2010Knowx innovation14
  • 20.
    File handlingAccomplished throughthe standard C libraryWe can create and manipulate ASCII text or binary files with the same API.APIfopen, fclose, fwrite , fread, fseek, and rewind.12 January 2010Knowx innovation15
  • 21.
    fopen Opening afile can also be the mechanism to create a fileprototype:FILE * fopen(const char *filename,const char *mode)filename - file we wish to access or createmode – mode we wish to useFILE * - fopen returns the FILE pointer (FILE *) 12 January 2010Knowx innovation16
  • 22.
    ExampleFILE *fin; fin= fopen("inpfile.txt", "r"); 12 January 2010Knowx innovation17
  • 23.
    Program#include <stdio.h> #defineMYFILE "missing.txt" main() {FILE *fin; fin = fopen( MYFILE, "r" ); /* Try to open the file for read */ if (fin == (FILE *)0) /* Check for failure to open */ {printf(“error in opening file”); /* Emit an error message and exit */exit(-1);} fclose( fin ); /* All was well, close the file */ }12 January 2010Knowx innovation18
  • 24.
    fread() and fwrite()Prototypes:size_t fread(void *ptr, size_t size, size_t nmemb,FILE *stream);size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);fseek()Prototype:int fseek (FILE * stream, long offset, int whence);Function allows to the new position given an indexwhence argument defines 12 January 2010Knowx innovation19
  • 25.
    SEEK_SET - moves the file position to the position defined by offsetSEEK_CUR -moves the file position the number of bytes defined by offset from the current file positionSEEK_END - moves the file position to the number of bytes defined by offset from the end of the filerewind ()Resets the file read pointer back to the start of the filePrototypevoid rewind (FILE * stream);12 January 2010Knowx innovation20
  • 26.
    Program#include <stdio.h>#define MAX_LINE40 #define FILENAME "myfile.txt“typedef struct { int id; float x_coord; float y_coord; char name[MAX_LINE+1]; }MY_TYPE_T; MY_TYPE_T object;int main() {int i;FILE *fin; fin = fopen( FILENAME, "r" ); /* Open the input file */12 January 2010Knowx innovation21
  • 27.
    if (fin== (FILE *)0) exit(-1);fseek( fin, (2 * sizeof(MY_TYPE_T)), SEEK_SET ); /* Get the last entry */fread( &object, sizeof(MY_TYPE_T), 1, fin ); printf("%d %f %f %s\n", object.id, object.x_coord, object.y_coord, object.name );rewind( fin ); /* Get the second to last entry */ fseek( fin, (1 * sizeof(MY_TYPE_T)), SEEK_SET );fread( &object, sizeof(MY_TYPE_T), 1, fin );printf("%d %f %f %s\n", object.id, object.x_coord, object.y_coord, object.name ); 12 January 2010Knowx innovation22
  • 28.
    /* Get thefirst entry */rewind( fin ); fread( &object, sizeof(MY_TYPE_T), 1, fin ); printf("%d %f %f %s\n", object.id, object.x_coord, object.y_coord, object.name ); fclose( fin );return 0; } 12 January 2010Knowx innovation23
  • 29.
    getpid() - to get the current process ID.getppid() - to get the parent process ID.getuid() - to get the user ID.getgid() - to get the group ID.12 January 2010Knowx innovation24
  • 30.
    Program#include <stdio.h> #include<unistd.h> #include <sys/types.h> int main(){pid_t myPid; pid_t myParentPid; gid_t myGid; uid_t myUid; myPid = getpid(); myParentPid = getppid(); myGid = getgid();12 January 2010Knowx innovation25
  • 31.
    myUid = getuid(); printf( "my process id is %d\n", myPid ); printf( "my parent's process id is %d\n", myParentPid );printf( "my group id is %d\n", myGid );printf( "my user id is %d\n", myUid ); return 0; } Outputmy process id is 10932.my parents process id is 10795My group id is 500My user id is 50012 January 2010Knowx innovation26
  • 32.
    Process apiForkCreate anew child processWaitSuspend execution until a child processes exitsSignalInstall a new signal handlerExecReplace the current process image with a new process image12 January 2010Knowx innovation27
  • 33.
    ForkCreating new processeswith in a given process.return value of fork is greater than zero then in the parent context. Equal to zero then in the child context.less than zero then error occurred.12 January 2010Knowx innovation28
  • 34.
    Examplepid_t pid;pid =fork();if(pid>0) {/*parent context*/}else if (pid ==0) {/*child context*/}else{/*error occurred no child created*/}12 January 2010Knowx innovation29
  • 35.
  • 36.
    Program#include <sys/types.h> #include<sys/wait.h> #include <unistd.h>#include <stdio.h> #include <errno.h> int main() {pid_t ret; int status, I, role = -1;12 January 2010Knowx innovation31
  • 37.
    ret = fork();if (ret > 0) { printf("Parent: This is the parent process (pid %d)\n", getpid()); for (i = 0 ; i < 6 ; i++) { printf("Parent: At count %d\n", i); sleep(1); } ret = wait( &status ); role = 0; }else if (ret == 0) { printf("Child: This is the child process (pid %d)\n", getpid()); 12 January 2010Knowx innovation32
  • 38.
    for (i =0 ; i < 6 ; i++) {printf("Child: At count %d\n", i); sleep(1); } role = 1; }else { printf("Parent: Error trying to fork() (%d)\n", errno); }printf("%s: Exiting...\n", ((role == 0) ? "Parent" : "Child")); return 0; } 12 January 2010Knowx innovation33
  • 39.
    waitSuspend the callingprocess until a child process(created by this process) exits or until a signal is delivered.Prototypepid_t wait (int *status);12 January 2010Knowx innovation34
  • 40.
    SignalInstall a signalhandler for a process.Prototypesighandler_t signal (int signum, sighandler_t handler);SIGHUP - hang up –commonly used to restart a task.SIGKILL - kill signalSIGINT - interrupt from the keyboardSIGSTOP – stop processSIGQUIT – quit signal from keyboard12 January 2010Knowx innovation35
  • 41.
    Program#include <stdio.h> #include<sys/types.h>#include <sys/wait.h>#include <unistd.h> #include <signal.h>#include <errno.h> void usr1_handler( int sig_num ) { printf( "Process (%d) got the SIGUSR1\n", getpid() ); }int main() { pid_t ret;int status role = -1; signal( SIGUSR1, usr1_handler ); 12 January 2010Knowx innovation36
  • 42.
    ret = fork();if(ret > 0) { /* Parent Context */printf( "Parent: This is the parent process (pid %d)\n", getpid() ); role = 0; pause(); printf( "Parent: Awaiting child exit\n" );ret = wait( &status );}12 January 2010Knowx innovation37
  • 43.
    else if (ret== 0) { /* Child Context */ printf( "Child: This is the child process (pid %d)\n", getpid() );role = 1; pause(); } else { /* Parent Context -- Error */ printf( "Parent: Error trying to fork() (%d)\n", errno ); }printf( "%s: Exiting...\n", ((role == 0) ? "Parent" : "Child") ); return 0;} 12 January 2010Knowx innovation38
  • 44.
    execReplaces the currentprocess image altogether.Once the exec function replaces the current process, its pid is the same as the creating processPermits the current process context to be replace with the program specifies as the first argument.12 January 2010Knowx innovation39
  • 45.
    Example execl(“/bin/ls”,”ls”,”-la”,null);This command replacesthe current process with the ls (list directory)Prototypes for the variants of execint execl (const char *path,const char * arg, …,..)int execlp(const char *path,const char *arg,……)int execv(const char *path, char *const argv[])int execvp(const char *file, char *const argv[])12 January 2010Knowx innovation40
  • 46.
    Program for shellinterpreter#include <sys/types.h> #include <sys/wait.h>#include <unistd.h>#include <stdio.h>#include <stdlib.h> #include <string.h> #define MAX_LINE 80 int main() {int status; pid_t childpid;char cmd[MAX_LINE+1]; char *sret;12 January 2010Knowx innovation41
  • 47.
    while (1){printf("mysh>"); sret = fgets( cmd, sizeof(cmd), stdin ); if (sret == NULL) exit(-1);cmd[ strlen(cmd)-1] = 0; if (!strncmp(cmd, "bye", 3)) exit(0);childpid = fork(); if (childpid == 0) { execlp( cmd, cmd, 0 ); }else if (childpid > 0) { waitpid( childpid, &status, 0 ); } printf("\n"); } return 0;} 12 January 2010Knowx innovation42
  • 48.
    Message queuesMessages aresmall collections of data (400 bytes, for example) that can be passed between cooperating programs through a message queue.Messages within a queue can be of different types, and any process with proper permissions can receive the messages.12 January 2010Knowx innovation43
  • 49.
    Creating message queueAPImsgget(key_k key , int msgflg)the key which signifies the name given to the queueflags argument must contain the permission bits for the new queueIPC_CREAT if the queue is being createdIPC_EXCL return an error if the message queue already existsReturn the msgidExample msgget(111 , 0666 | IPC_CREAT);12 January 2010Knowx innovation44
  • 50.
    Program#include <stdio.h> #include<sys/msg.h>#define MY_MQ_ID 111int main(){int msgid;/* Create the message queue with the id MY_MQ_ID */ msgid = msgget( MY_MQ_ID, 0666 | IPC_CREAT ); if (msgid >= 0) { printf( "Created a Message Queue %d\n", msgid ); }return 0;} 12 January 2010Knowx innovation45
  • 51.
    Sending the messageAPIintmsgsnd (int msqid, const void *msgp, size_t msgsz, int msgflg); Takes 4 parametersmsqid is the queue id of the existing queue.msgp is the pointer that contains the address of the structure that holds the message and type.struct message{ long mtype; //The message type.prioritychar mesg [MSGSZ];//The message is of length MSGSZ. }; 12 January 2010Knowx innovation46
  • 52.
    MSGSZ is thelength of the message sent in bytes.MSGFLG specifies the action to be taken if one or more of the following are true.The number of bytes already in the queue is equal to msg_qbytes.The total number of messages on all queues on the system has reached a maximum limitAction to be takenIf (msgflg & IPC_NOWAIT) is non-zero, the message will not be sent and the calling process will return immediatelyIf (msgflg & IPC_NOWAIT) is 0, the calling process will suspend execution until one of the following occurs: 12 January 2010Knowx innovation47
  • 53.
    Program#include <sys/types.h> #include<sys/ipc.h> #include <sys/msg.h>#include <stdio.h> #include <string.h> #define MSGSZ 128 typedef struct msgbuf /* will hold the message to be put in the queue */{ long mtype; /* priority of message */char mtext[MSGSZ]; /* the message that is stored */ }message_buf; main() { int msqid; int msgflg = IPC_CREAT | 0666; key_t key; message_buf sbuf; size_t buf_length; key = 10;printf("Calling msgget with key %#lx and flag %#o\n",key,msgflg);12 January 2010Knowx innovation48
  • 54.
    /*A queue iscreated using the msget function with a key value 10 and the flag parameter being IPC_CREAT|06668 */ if ((msqid = msgget(key, msgflg )) < 0){ perror("msgget"); exit(1); } else printf("msgget: msgget succeeded: msqid = %d\n", msqid); sbuf.mtype = 1; /*setting the priority as 1 */printf("msgget: msgget succeeded: msqid = %d\n", msqid);(void) strcpy(sbuf.mtext, "I am in the queue?"); /* copy the text "I am in the queue" into the array mtext which is message array */printf("msgget: msgget succeeded: msqid = %d\n", msqid);12 January 2010Knowx innovation49
  • 55.
    buf_length =strlen(sbuf.mtext) + 1 ; /*sending the message with option IPC_NOWAIT */if (msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) < 0){ printf ("%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buf_length); perror("msgsnd"); exit(1); } else printf("Message: \"%s\" Sent\n", sbuf.mtext); exit(0); }12 January 2010Knowx innovation50
  • 56.
    Receive the messageAPIintmsgrcv (int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);Arguments-msqid is the queue id of the existing queue.msgp is the point to a receiving buffer large enough to hold the received messagemsgszthe maximum size of the received message12 January 2010Knowx innovation51
  • 57.
    program#include <sys/types.h> #include<sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #define MSGSZ 128 typedef struct msgbuf /* structure that will hold the message obtained from the queue*/{ long mtype; /*priority of message */ char mtext[MSGSZ]; /*message that stored */} message_buf;main() {12 January 2010Knowx innovation52
  • 58.
    int msqid;key_t key; message_buf rbuf; key = 10;/*creating a queue with the key value 10, */if ((msqid = msgget(key, 0666)) < 0){ perror("msgget"); exit(1); } /*acquires the message from the queue into rbuf*/if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0) < 0) { perror("msgrcv");exit(1); }printf("%s\n", rbuf.mtext); exit(0); } 12 January 2010Knowx innovation53
  • 59.
    Configuring message queueAPImsgctl(intmsqid, int cmd, struct msqid_ds *buf)3 Arguments msqid is the queue id cmd is a command constant*bufis a pointer to structure.Use to get the info about a message queueSet the info for a message queueRemove a message queue12 January 2010Knowx innovation54
  • 60.
  • 61.
    Variable that isprotected.It provides a means to restrict access to a resource that is shared amongst two or more processesTwo operations are permitted , called acquire and release.2 types of semaphore.Binary and Counting 12 January 2010Knowx innovation56Semaphore
  • 62.
    The signal notationsP(semaphorevariable) for waitV(semaphore variable) for signal12 January 2010Knowx innovation57
  • 63.
    A binary semaphoreis a variable that can take only the values 0 and 1.Represents a single resource and therefore when one process has acquired it,others are blocked until it is released.P(sv) if sv greater than 0 , decrement sv.ifsvis zero suspend execution of the processV(sv) if other process has been suspended waiting for sv, make it resume.if no waiting, increment sv12 January 2010Knowx innovation58Binary semaphore
  • 64.
  • 65.
    Represent shared resourcesin quantities greater than one.It could represent the entire set of buffers by setting its value to the number of buffers available.Whenever the process acquires the semaphore, the value decrement .When the semaphore value reaches zero, process are blocked until it becomes a non zero.12 January 2010Knowx innovation60Counting semaphore
  • 66.
  • 67.
    Creating semaphoreAPIsemget( key_tkey, int num_sems, int sem_flags)Key is the semaphore keyNum_sems is the Semaphore countFlags To acquire or release of semaphoreAPIsemop(int sem_id, struct sembuf *sem_ops,size_tnum_sem_ops)12 January 2010Knowx innovation62
  • 68.
    sem_id, is thesemaphore identifier, as returned from semget.sem_ops, is a pointer to an array of structures, each of which will have at least the following members:Struct sembuf{short sem_num;short sem_op;short sem_flg;}12 January 2010Knowx innovation63