Top Banner
Linux Monday, May 16, 2022 Knowx innovation 1
68
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Linux

April 8, 2023 Knowx innovation 1

Linux

Page 2: Linux

April 8, 2023 Knowx innovation 2

Unix

• Developed at Bell Labs in late 1960s

• Owned by AT&T at the time, which meant you had to buy it once AT&T figured out it was valuable

• Written in C (a high level language)

• Needs to be compiled to run

• Can be easily moved to a different system by re-compiling for new hardware

Page 3: Linux

April 8, 2023 Knowx innovation 3

Why Linux

• Entire OS source code is free• Full 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, NUMA

Page 4: Linux

April 8, 2023 Knowx innovation 4

• Protected memory• True multiuser capabilities• Filesystem choices:ext3, JFS, XFS, reiserFS• Highly modular & scalable: From embedded

systems to IBM mainframes

Page 5: Linux

April 8, 2023 Knowx innovation 5

distribution

• Debian (related: Knoppix, (k)ubuntu, Mepis, Xandros)

• RedHat (related: Fedora, CentOS)• SUSE (related: OpenSUSE)• Mandriva• Slackware• Embedded Linuxes

Page 6: Linux

April 8, 2023 Knowx innovation 6

GNU/Linux architecture

Page 7: Linux

April 8, 2023 Knowx innovation 7

• Linux kernel– Mediates access to the hardware and peripherals

• Shells – Provides user access to the kernel

• Applications – Provide the useful function for the operating

system

Page 8: Linux

April 8, 2023 Knowx innovation 8

Kernel architecture

Page 9: Linux

April 8, 2023 Knowx innovation 9

Gnu compiler collection(gcc)

• Compiler and set of utilities to build binaries from high level source code.

• Standard for embedded systems development– Since its supports so many different target

architectures• Supports a number of languages– C, C++, ada, java, FORTRAN, Pascal

Page 10: Linux

April 8, 2023 Knowx innovation 10

Stage of compilation

Page 11: Linux

April 8, 2023 Knowx innovation 11

stage input output GCC example

preprocessing *.c *.i gcc –E test.c

Compiling *.i *.s gcc –S test.i

Assembling *.s *.o gcc –c test.s

Linking *.o gcc test.o

Page 12: Linux

April 8, 2023 Knowx innovation 12

makefile

Page 13: Linux

April 8, 2023 Knowx innovation 13

• make utility uses a developer-created input file to describe the project built

• GNU uses the name Makefile as the default name for its input file.

Page 14: Linux

April 8, 2023 Knowx innovation 14

appexp : main.o app.o bar.o lib.o

gcc –o appexp main.o app.o bar.o lib.o

main.o : main.c lib.h app.h

gcc –c -o main.o main.c

app.o: app.c lib.h app.h

gcc –c -o app.o app.c

bar.o : bar.c lib.h

gcc –c -o bar.o bar.c

lib.o : lib.c lib.h

gcc –c -o lib.o lib.c

Line 1: is the rule

The portion of the rule before the colon is called target and after the colon is called dependencies.

Page 15: Linux

April 8, 2023 Knowx innovation 15

File handling

• Accomplished through the standard C library

• We can create and manipulate ASCII text or binary files with the same API.

• API– fopen, fclose, fwrite , fread, fseek, and rewind.

Page 16: Linux

April 8, 2023 Knowx innovation 16

• 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 create

mode – mode we wish to use

FILE * - fopen returns the FILE pointer (FILE *)

Page 17: Linux

April 8, 2023 Knowx innovation 17

• Example

FILE *fin;

fin = fopen("inpfile.txt", "r");

MODE Description

r Open an existing file for readw Open a file for write (create new if exists)a Open a file for append (create if file doesn’t

exist)

rw Open for read write (create if it doesn’t exist)

Page 18: Linux

April 8, 2023 Knowx innovation 18

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 */

}

Page 19: Linux

April 8, 2023 Knowx innovation 19

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 index– whence argument defines

Page 20: Linux

April 8, 2023 Knowx innovation 20

SEEK_SET - moves the file position to the position defined by offset

SEEK_CUR - moves the file position the number of bytes defined by offset from the current file position

SEEK_END - moves the file position to the number of bytes defined by offset from the end of the file

rewind ()– Resets the file read pointer back to the start of the file

Prototype

void rewind (FILE * stream);

Page 21: Linux

April 8, 2023 Knowx innovation 21

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 */

Page 22: Linux

April 8, 2023 Knowx innovation 22

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 );

Page 23: Linux

April 8, 2023 Knowx innovation 23

/* 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;

}

Page 24: Linux

April 8, 2023 Knowx innovation 24

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.

Page 25: Linux

April 8, 2023 Knowx innovation 25

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();

Page 26: Linux

April 8, 2023 Knowx innovation 26

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;

}

Output

my process id is 10932.

my parents process id is 10795

My group id is 500

My user id is 500

Page 27: Linux

April 8, 2023 Knowx innovation 27

Process api

• Fork– Create a new child process

• Wait– Suspend execution until a child processes exits

• Signal– Install a new signal handler

• Exec– Replace the current process image with a new

process image

Page 28: Linux

April 8, 2023 Knowx innovation 28

Fork

• Creating 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.

Page 29: Linux

April 8, 2023 Knowx innovation 29

Example

pid_t pid;

pid = fork();

if(pid>0)

{/*parent context*/}

else if (pid ==0)

{/*child context*/}

else

{/*error occurred no child created*/}

Page 30: Linux

April 8, 2023 Knowx innovation 30

Page 31: Linux

April 8, 2023 Knowx innovation 31

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;

Page 32: Linux

April 8, 2023 Knowx innovation 32

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());

Page 33: Linux

April 8, 2023 Knowx innovation 33

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;

}

Page 34: Linux

April 8, 2023 Knowx innovation 34

wait

• Suspend the calling process until a child process(created by this process) exits or until a signal is delivered.

Prototype

pid_t wait (int *status);

Page 35: Linux

April 8, 2023 Knowx innovation 35

Signal• Install a signal handler for a process.Prototype

sighandler_t signal (int signum, sighandler_t handler);

SIGHUP - hang up –commonly used to restart a task.

SIGKILL - kill signal

SIGINT - interrupt from the keyboard

SIGSTOP – stop process

SIGQUIT – quit signal from keyboard

Page 36: Linux

April 8, 2023 Knowx innovation 36

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 );

Page 37: Linux

April 8, 2023 Knowx innovation 37

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 );

}

Page 38: Linux

April 8, 2023 Knowx innovation 38

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;

}

Page 39: Linux

April 8, 2023 Knowx innovation 39

exec

• Replaces the current process image altogether.• Once the exec function replaces the current

process, its pid is the same as the creating process

• Permits the current process context to be replace with the program specifies as the first argument.

Page 40: Linux

April 8, 2023 Knowx innovation 40

Example

execl(“/bin/ls”,”ls”,”-la”,null);

This command replaces the current process with the ls (list directory)

Prototypes for the variants of exec

int 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[])

Page 41: Linux

April 8, 2023 Knowx innovation 41

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;

Page 42: Linux

April 8, 2023 Knowx innovation 42

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;

}

Page 43: Linux

April 8, 2023 Knowx innovation 43

Message queues

• Messages 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.

Page 44: Linux

April 8, 2023 Knowx innovation 44

Creating message queue

API

msgget(key_k key , int msgflg)– the key which signifies the name given to the queue– flags argument must contain the permission bits for

the new queue• IPC_CREAT if the queue is being created• IPC_EXCL return an error if the message queue already

exists

– Return the msgid

Example

msgget(111 , 0666 | IPC_CREAT);

Page 45: Linux

April 8, 2023 Knowx innovation 45

• Program

#include <stdio.h>

#include <sys/msg.h>

#define MY_MQ_ID 111

int 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;

}

Page 46: Linux

April 8, 2023 Knowx innovation 46

Sending the message

API

int msgsnd (int msqid, const void *msgp, size_t msgsz, int msgflg); – Takes 4 parameters– msqid 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.priority

char mesg [MSGSZ];//The message is of length MSGSZ. };

Page 47: Linux

April 8, 2023 Knowx innovation 47

– 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 limit

– Action to be taken• If (msgflg & IPC_NOWAIT) is non-zero, the message will

not be sent and the calling process will return immediately• If (msgflg & IPC_NOWAIT) is 0, the calling process will

suspend execution until one of the following occurs:

Page 48: Linux

April 8, 2023 Knowx innovation 48

• 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);

Page 49: Linux

April 8, 2023 Knowx innovation 49

/*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);

Page 50: Linux

April 8, 2023 Knowx innovation 50

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);

}

Page 51: Linux

April 8, 2023 Knowx innovation 51

Receive the message

API

int 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 message–msgsz the maximum size of the received

message

Page 52: Linux

April 8, 2023 Knowx innovation 52

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()

{

Page 53: Linux

April 8, 2023 Knowx innovation 53

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);

}

Page 54: Linux

April 8, 2023 Knowx innovation 54

Configuring message queue

APImsgctl(int msqid, int cmd, struct msqid_ds *buf)

– 3 Arguments – msqid is the queue id – cmd is a command constant– *buf is a pointer to structure.

– Use to get the info about a message queue– Set the info for a message queue– Remove a message queue

Page 55: Linux

April 8, 2023 Knowx innovation 55

Page 56: Linux

April 8, 2023 Knowx innovation 56

• Variable that is protected.• It provides a means to restrict access to a

resource that is shared amongst two or more processes

• Two operations are permitted , called acquire and release.

• 2 types of semaphore.– Binary and Counting

Semaphore

Page 57: Linux

April 8, 2023 Knowx innovation 57

• The signal notations– P(semaphore variable) for wait– V(semaphore variable) for signal

Page 58: Linux

April 8, 2023 Knowx innovation 58

• 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.if sv is zero suspend execution of the process

• V(sv) if other process has been suspended waiting for sv, make it resume.if no waiting, increment sv

Binary semaphore

Page 59: Linux

April 8, 2023 Knowx innovation 59

Page 60: Linux

April 8, 2023 Knowx innovation 60

• 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.

Counting semaphore

Page 61: Linux

April 8, 2023 Knowx innovation 61

Page 62: Linux

April 8, 2023 Knowx innovation 62

Creating semaphore

API

semget ( key_t key, int num_sems, int sem_flags)– Key is the semaphore key– Num_sems is the Semaphore count– Flags

To acquire or release of semaphore

APIsemop(int sem_id, struct sembuf *sem_ops,size_t num_sem_ops)

Page 63: Linux

April 8, 2023 Knowx innovation 63

– 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;

}

Page 64: Linux

April 8, 2023 Knowx innovation 64

• Program to acquire the semaphore.#define MY_SEM_ID 111

#define MY_SEMARRAY_ID 112

#define NUM_SEMAPHORES 10

#include <stdio.h>

#include <sys/sem.h>

#include <stdlib.h>

#include "common.h"

int main()

{

int semid;

struct sembuf sb;

/* Get the semaphore with the id MY_SEM_ID */

semid = semget( MY_SEM_ID, 1, 0 );

Page 65: Linux

April 8, 2023 Knowx innovation 65

if (semid >= 0)

{

sb.sem_num = 0;

sb.sem_op = -1;

sb.sem_flg = 0;

printf( "semacq: Attempting to acquire semaphore %d\n", semid );

/* Acquire the semaphore */

if (semop( semid, &sb, 1 ) == -1)

{

printf("semacq: semop failed.\n");

exit(-1);

}

printf( "semacq: Semaphore acquired %d\n", semid );

}

return 0;

}

Page 66: Linux

April 8, 2023 Knowx innovation 66

Program to release the semaphore.#define MY_SEM_ID 111

#define MY_SEMARRAY_ID 112

#define NUM_SEMAPHORES 10

#include <stdio.h>

#include <sys/sem.h>

#include <stdlib.h>

#include "common.h"

int main()

{

int semid;

struct sembuf sb;

/* Get the semaphore with the id MY_SEM_ID */

semid = semget( MY_SEM_ID, 1, 0 );

Page 67: Linux

April 8, 2023 Knowx innovation 67

if (semid >= 0)

{

printf( "semrel: Releasing semaphore %d\n", semid );

sb.sem_num = 0;

sb.sem_op = 1;

sb.sem_flg = 0;

/* Release the semaphore */

if (semop( semid, &sb, 1 ) == -1)

{

printf("semrel: semop failed.\n");

exit(-1);

}

printf( "semrel: Semaphore released %d\n", semid );

}

return 0;

}

Page 68: Linux

April 8, 2023 Knowx innovation 68