Created by Amit S

Title of Assignment: Shell programming and AWK programming with suitable application (student database) and use of advanced filters and report generation.

Relevant Theory / Literature Survey: (Brief Theory Expected) About Shell: The shell is a command interpreter that provides a line-oriented interactive and noninteractive interface between the user and the operating system. You enter commands on a command line; they are interpreted by the shell and then sent as instructions to the operating system. The Shell makes available three files. 1)Standard input 2)Standard Output 3)Standard Error

It can manipulate the default source and destination of input and output streams by assigning them to disk files. How it Works: (1)Parsing : The shell first breaks up the command line into words using spaces and tabs as delimiters, unless quoted. All consecutive occurrence of a space or tabs is replaced with single space. (2)Variable Evaluation : All $-prefixed strings are evaluated as variables, unless quoted or escaped. (3)Command Substitution : Any command surrounded by back quotes is executed by the shell, which then replaces standard output of the command into command line. (4)Redirection : The shell then looks for the characters >, < and >> to open the files they point to. (5)Wild-card interpretation : The shell finally scans the command line for wild-cards (*, ?, [ and ] ). Any word containing a wild-card is replaced by a sorted list of file names that match the pattern. The list of these filenames then forms arguments to the command. (6)PATH evaluation : It finally looks for the PATH variable to determine the sequence of directories it has to search in order to hunt for the command.

Linux Shell : Shell accepts user instruction or commands and if its a valid command it is passed to kernel. Shell provides an environment for user interaction. Shell is a command language interpreter that executes commands read from the standard input device or from a file. Shell is not part of system kernel but uses the system kernel to execute programs.

Created by Amit S

Several shells available with Linux are as below. BASH ( Bourne-Again SHell ) : Most commonly used shell in Linux. It is Freeware shell. It was developed by Brian Fox and Chet Ramey at Free Software Foundation. CSH (CShell) : The C shell's syntax and usage are very similar to the C programming language. It was developed by Bill Joy at University of California (For BSD). KSH (Korn Shell) : It was developed by David Korn AT & T Bell Labs. TCSH : TCSH is an enhanced but completely compatible version of the Berkeley UNIX C shell. To find all available shells in the system use the following command $ cat /etc/shells To find the current shell use the following command $ echo $SHELL Shell Script : Shell Script is series of command written in plain text file. Shell script is just like batch file is MS-DOS. Steps required to write shell script: 1. Use any editor like vi or mcedit to write shell script. 2. After writing shell script set execute permission for user written script by using chmod command. Ex: chmod permission script-name Comments : Comments in shell programming start with # and go until the end of the line. Variables in Shell : In shell programming all variables have the data type string and no need to declare them. There are two types of variable. 1. System variables : Created and maintained by Linux itself. These variables are defined in capital letters. 2. User defined variables (UDV) : Created and maintained by user. This type of variable is defined in lower letters. In shell program there are also environment variables which are preceded by the keyword export. Shell commands and control structures:There are three categories of commands which can be used in shell scripts: 1) Unix commands: Shell script can make use of any unix commands. Some of the commands which are more often used than others are as below. Command syntax Purpose

Created by Amit S

echo "some text" Ls wc -l file wc -w file wc -c file cp sourcefile destfile grep 'pattern' file


write some text on your screen list files count lines in file or count words in file or count number of characters copy sourcefile to destfile search for strings in a file Example: grep 'searchstring' file.txt Most of the time awk is used to extract fields from a text line. The default field separator is space. To specify a different one use the option -F. cat file.txt | awk -F, '{print $1 "," $3 }'

2) Pipes and redirection Pipes (|): send the output of one program to the input of another program. Ex.: grep "hello" file.txt | wc -l It is used to find the lines with the string hello in file.txt and then counts the lines. The output of the grep command is used as input for the wc command. Redirection: writes the output of a command to a file or appends data to a file > writes output to a file and overwrites the old file in case it exists >> appends data to a file or creates a new one if it doesn't exist already but it never overwrites anything. 3) Control structures "if" statement : It tests the condition and if the condition is true "then" part gets executed otherwise else part is executed. if ....; then .... elif ....; then .... else .... fi case statement : It can be used to match a given string against a number of possibilities. case ... in ...) do something here;; esac Loop statements :The while-loop will run while the expression given if it is true. The keyword "break" can be used to leave the loop at any point in time. With the keyword

and perform actions on files. Field zero ($0) refers to the entire line. searching each line to see if it matches a set of patterns or conditions specified in the awk program. and the dollar symbol ($) is used to represent a field. it breaks it down into a number of fields. awk scans lines from a file(s) or standard input. printf: Built in function of awk called printf operates the same way as in the C programming .. Fields are numbered beginning at one.Created by Amit S "continue" the loop continues with the next iteration and skips the rest of the loop body. an action is specified.blogspot....Programs in awk are different from programs in most other languages. STRUCTURE OF AN AWK PROGRAM : awk scans input lines one after the other. For each pattern. pattern { action } pattern { action } When awk scans an input line. for var in ..... Thus. expr . expr ) statement for ( var in array ) statement do statement while ( expr) avscomputer.. done The for-loop takes a list of strings (strings separated by space) and assigns them to a variable. Brackets are used to enclose the argument. match patterns. do . do . an awk program consists of a number of patterns and associated actions. while . awk Control Flow Statements : if ( expr) statement [ else statement] if ( subscript in array) statement [ else statement] while ( expr) statement for ( expr . because awk programs are data-driven. done AWK: awk is a programming language designed to search for.. Actions are enclosed using curly braces and separated using semi-colons.. It is terminated by a semi-colon. The action is performed when the pattern matches that of the input line. Fields are separated by a space or tab character... and the text is enclosed using double quotes.

c 4096 .c 4096 .sh SIZE FILE NAME 4096 .temp.a.File_Manage.out 4096 .db.Created by Amit S # Shell Program for Listing Files in Current Dir # Whose size >= 4096 Bytes echo "SIZE FILE NAME" SizeLimit=4 count=0 for f in * # for all files in current Directory do if test -f $f # Check file Types and compare values then fsize=`ls -s $f |awk '{print $1} '` if test $fsize -ge $SizeLimit then csize=`expr $fsize \* 1024` echo $csize .txt 4096 .awk 16384 .fork1.txt 4096 .txt Total Number of Files:: 14 Conclusion: Studied the various shell programming and AWK commands and their use for generation of required output.thread_a./file_size. avscomputer.$f count=$[count+1] fi fi done echo "Total Number of Files:: $count" root@localhost Unix_Pro]# .c 4096 .sh 4096 .out.c 4096 .t_join.awk 4096 .db.c 16384 .child_process.z.file_size.txt 4096 .log 4096 .

Relevant Theory / Literature Survey: (Brief Theory Expected) Process: Process is an active entity that executes a given piece of code. such as text. and each process alocated a user area that contains private data manipulated only by the kernel. Process States and Transitions : avscomputer. The process table contains (or points to) per process region table.blogspot.Created by Amit S Title of Assignment: Using fork system call. Several processes may be executing the same or different program at the same time for the same user or for several different users. own set of memory pages. Data Structures for Process : Every process has an entry in the kernel process table. whose entries point to entries in the region table. It has its own execution .A region table is a contiguous area of process address's space. suspend it using wait system call and transfer it into zombie state. data and stack. own file descriptors table and a unique process ID. create child process.

the modification will only affect the variable in the parent process's address space. The process ID is an integer. In other words. When the main program executes fork(). if the parent changes the value of its variable. Every process has an entry in the The identification of the parent from the child can be done by testing the returned value of fork(). Since both processes have identical but separate address spaces. is created.blogspot. Other address spaces created by fork() calls will not be affected even though they have identical variable names. those variables initialized before fork() call have the same values in both address spaces. which becomes the child process of the caller. including the program and all data. Since every process has its own address space. to the parent. The purpose of fork() is to create a new process. an identical copy of its address space. fork() returns a positive value. Unix will make an exact copy of the parent’s address space and give it to the child. A process can use function getpid() to retrieve the process ID assigned to this process. It takes no arguments and returns a process ID. So the parent and child processes have separate address spaces.Created by Amit S Fork() : This system call is used to create processes. any modifications will be independent of the others. avscomputer. fork() returns a zero to the newly created child process. the process ID of the child process. the creation of a child process is unsuccessful. After a new child process is created. • • • If fork() returns a negative . both processes will execute the next instruction following the fork() system call.

the caller resumes its execution. the caller will be blocked until one of its child processes exits.Created by Amit S System call fork() returns the child process ID to the parent and returns 0 to the child process. and only then the child process is completely removed from the system. the child remains in the zombie state forever. the call returns immediately. and then the call return with the exit status of the child process. exit() : This system call is used to terminate the current process. or the child exits before the parent. When wait() is called. it is not immediately cleared off from the process table. wait() takes the address of an integer variable and returns the process ID of the completed process. When the parent process is not properly coded. the child process is in a state called "zombie". Instead. If it has a zombie child process. If there are at least one child processes running when the call to wait() is made. If there is no child process running when the call to wait() is made. At that moment. When a child process exits. with the exit status of that process. One of the main purposes of wait() is to wait for completion of child processes. then this wait() has no effect at all. Such processes can be noticed by running the 'ps' command (shows the process list) and seeing processes having string "<defunct>" as their command . a signal is sent to its parent process. there are two possibilities. The simple way of a process to acknowledge the death of a child process is by using the wait() system call. The execution of wait() could have two possible situations. avscomputer. wait() :This system call blocks the calling process until one of its child processes exits or a signal is received. Some flags that indicate the completion status of the child process are passed back with the integer pointer. it is as if no wait() is there.The exit code or return code is a numeric value returned by a terminating process to its parent process.blogspot. 2. Zombie state of process : Once a child process is created . the process is suspended until one of its child processes exits. That is. which needs to acknowledge it's child's death. In the duration before the parent's acknowledgment and after the child's exit. 1. Either the parent process exits before the child.

identification of child and parent . suspension of a process and transferring the process to zombie state. avscomputer.Created by Amit S Conclusion: Studied the creation of a child process.blogspot.

h> #include<sys/ . } exit(0). pid_t pid.h> #include<stdio.b. i += 2. pid = fork(). i += 2.Created by Amit S Addition of six numbers……………………………… #include<unistd.5. pid_t child_pid.3. if(pid == 0) { c = x[i] + x[i+1].6}. } avscomputer. pid = fork(). int a. i += 2.h> #include<stdlib.h> int main() { int x[6] = {1.2. } } } } } if(pid != 0) { int stat_val.4.blogspot.c). pid = fork(). printf("\nSUM = %d\n". if(pid == 0) { a = a + b. pid = fork(). if(pid == 0) { a = x[i] + x[i+1]. static int i = 0 . if(pid == 0){ b = x[i] + x[i+1]. pid = fork(). child_pid = wait(&stat_val). if(pid == 0){ c = a + c.c.

0 0 0 ? SW 03:33 0:02 [kjournald] root 75 0.2 4356 1440 pts/0 S 03:34 0:00 bash avscomputer.0 0.0 0.0 0.0 0.0 0 0 ? SW 03:32 0:00 [migration/0] root 3 0.0 0.0 0 0 ? SW 03:33 0:00 [keventd] root 5 0.1 1444 548 ? S 03:33 0:00 syslogd -m 0 root 4133 0.0 0.0 0.0 0.0 0.0 0.0 0 0 ? SWN 03:33 0:00 [ksoftirqd_CPU1] root 11 0.0 0.3 7496 1916 ? S 03:33 0:00 cupsd root 4408 0.0 1348 396 tty2 S 03:33 0:00 /sbin/mingetty tty2 root 4427 0.0 0.0 1348 396 tty3 S 03:33 0:00 /sbin/mingetty tty3 root 4428 0.0 0.0 1348 396 tty4 S 03:33 0:00 /sbin/mingetty tty4 root 4429 .0 0.0 0.0 1372 476 ? S 03:32 0:05 init root 2 0.0 0.0 0 0 ? SW 03:33 0:00 [kscand/DMA] root 9 0.3 0.0 0 0 ? SW 03:33 0:00 [kjournald] root 4129 0.0 root 4301 0.1 1396 608 ? SN 03:33 0:00 anacron -s root 4425 0.0 0 0 ? SW 03:32 0:00 [migration/1] root 4 0.0 0.0 0 0 ? SW 03:33 0:00 [kupdated] root 13 0.0 1348 396 tty1 S 03:33 0:00 /sbin/mingetty tty1 root 4426 0.0 1348 396 tty5 S 03:33 0:00 /sbin/mingetty tty5 root 4430 0.0 0 0 ? SW 03:33 0:00 [bdflush] root 7 0.0 0.0 0.1 1416 568 ? S 03:33 0:00 crond root 4340 0.0 0 0 ? SW 03:33 0:00 [mdrecoveryd] root 17 0.Created by Amit S ER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.blogspot.0 0 0 ? SWN 03:33 0:00 [ksoftirqd_CPU0] root 6 0.0 0.0 0.0 0 0 ? SW 03:33 0:00 [kswapd] root 8 0.1 2024 864 ? S 03:33 0:00 xinetd -stayalive -reuse -pidfile /var/run/xinetd.0 0.0 0.0 1372 432 ? S 03:33 0:00 klogd -x root 4267 0.0 0 0 ? SW 03:33 0:00 [khubd] root 3874 0.0 0.0 0 0 ? SW 03:33 0:00 [kscand/Normal] root 10 0.0 1348 396 tty6 S 03:33 0:00 /sbin/mingetty tty6 root 4587 0.0 1412 444 ? S 03:33 0:00 gpm -t imps2 -m /dev/mouse root 4329 0.0 0 0 ? SW 03:33 0:00 [kscand/HighMem] root 12 0.4 5916 2496 ? S 03:33 0:00 [sendmail] root 4320 0.0 0.0 0.2 3508 1504 ? S 03:33 0:00 /usr/sbin/sshd root 4281 0.0 0.1 0.0 0.0 0.

out 0:00 ps ux Title of Assignment: avscomputer.0 0.0 0.2 0.2 0.0 0.5 0.0 0.blogspot.2 0.Created by Amit S root 4613 File_Manage.0 0./a.0 0.5 0.0 0.c root 4616 root 4731 root 4757 child_process.out 0:00 [a.0 0.0 .1 8048 2816 pts/0 4360 1444 pts/1 4368 1460 pts/2 8024 2816 pts/2 4364 1444 pts/3 1340 236 pts/1 0 0 pts/1 2656 708 pts/3 S S S S S S Z R 03:34 03:34 03:56 03:57 03:57 04:01 04:01 04:01 0:00 vim 0:00 bash 0:00 bash 0:00 vim 0:00 bash 0:00 .0 0.c root 4767 root 4807 root 4808 <defunct>] root 4809 0.

Relevant Theory / Literature Survey: (Brief Theory Expected) Unix file system is organized as a tree with single root node called root. read.blogspot. The inode contains the information necessary for a process to access a file like file ownership. Each file on unix system has a unique inode. reading the content of file. Unix provides system calls for creation of file. Processes access the files by a well defined set of system calls and specify the file by a character string that is the pathname. writing the information into the file etc. Every non-leaf node is of the file system is a directory of files and files at the leaf nodes of the tree are either . An Overview of the File Subsystem : Data Structures For File subsystem avscomputer. reading. regular files. deletion of file. lseek and fstat. open. creating. The name of the file is given by a pathname which describes how to locate the file in the system hierarchy. or special device files. file size and location of file’s data in the file system. writing operations of file are as below. Some of the system calls for accessing.Created by Amit S File management using low level file access system calls such as write. access rights.

When a process refers to a file by name. the kernel parses the file name one component at a time. After opening a file. which contains a description of the disk layout of the file data and other information. Each read or write system call increments a file location for a number of characters read or written. and eventually retrieves the inode for the file. (b) creat system call : avscomputer. Thus. the kernel assign it an unused inode. int openFlags).blogspot. The file location is set to 0. and reads them into an inode table when manipulating files. checks that process has permissions to search the directories in the path. Every file has one inode. The open file is logically connected to the file as mentioned in the open system call. the file is read (or/and written) sequentially by default. a negative integer is returned. When a process creates a new file. Syntax : int open (char * pathname. An open file has a file location associated with .Created by Amit S The internal representation of a file is given by inode. The File System Layout is as shown in the Figure (a) open system call : The open system call creates an operating system object called an open file. The flags can be one of the following: 0 – open for reading 1 – open for writing 2 – open for reading and writing If an error occurs in trying to open the file. It is the offset in the file where the next read or write will start. inodes are stored in the file system. read or write system calls are used to read or write the open file. but it may have several names (link). the open file identifier is returned. The named file is opened and a positive integer.

The file location is increased by the number of bytes read. the open file identifier is returned. (e) write system call : The operating system tries to write coun bytes to the open file designated by openFileID. int count). (d) read system call : The operating system tries to read count bytes from the open file designated by openFileID. The location into file is not passed with the call but it is kept with open file information as a part of the file state. A negative return value indicates some error occurred in the read. and from where to take and how many characters for writing. A negative return value indicates some error occurred in the write. thus no more bytes can be read. avscomputer. a negative integer is returned. but it does not indicate where in the file to write. int fileMode). The open file identifiers returned by open and creat are local to the process making the calls. an open file identifier in one process is not related to an open file identifier in another . int count). The file location is increased by the number of bytes read. Syntax: int read (int openFileID. The bytes are read from the file starting at the offset provided by the file location. The file mode defines file access rights. For causes of different negative values see man pages. This is not considered to be an error. The return value is the number of bytes that were actually read. If fewer then count bytes are left before the end of the file all remaining bytes are read. The bytes read are places into the array of bytes starting at bufferAddress. The return value is the number of bytes that were actually written.Created by Amit S The named file is created as an empty file and opened for writing and a positive integer. Syntax : int write (int openFileID. A return code 0 means the close succeeded. A return value -1 means that the openFileID did not refer to open file. char * bufferAddress. The bytes are taken from the array of bytes starting at bufferAddress. If an error occurs in trying to create the file. char * bufferAddress. A return value 0 indicates that the end of file has been reached and the file location is equal to the size of the file. Note that the write system call specifies into which file to write. Syntax : int close (int openFileID). The file location is set to 0. and this might be less than count. (c) close system call: The file is closed by using close system call. The bytes are written to the file starting at the offset provided by the file location.blogspot. Syntax : int creat (char * pathname. Thus.

The base is selected according to the moveMode as follows: 0 – use 0 as a base (move from the beginning of the file) 1 – use the current file location as a base (for relative move) 2 – use the current file size as a base (move from the end of the file). Syntax : int lseek (int openFileID. A return code 0 means the unlink . avscomputer. A 0 value will cause the next write to extend the file. Syntax : int unlink (char * pathname). inf offset. Close the open file using the close system call after completing the work with the open file. a negative integer is returned.blogspot. a negative integer is returned. If an error occurs in trying to delete a file. If an error occurs. The returned value is the new file position. The file location associated with the open file is changed to a new value. Positive values of the offset will cause the next write to be beyond the current end of the file. Conclusion: Studied various file system commands and their uses. (i) unlink system call : It is used to delete the file. int moveMode).Created by Amit S (f) lseek system call : It is used to achieve random access into the file since it changes the file location that will be used for the next read or write. An lseek with an offset of 0 and a moveMode of 1 will not change the file position but will return the current file position. The new value is computed by adding the offset to the base.

O_WRONLY). printf("\n\n-------..sizeof(buff)))>0) printf("%s"..buff).h> #include<stdlib.O_RDWR). fd=file_open(source.break. } int file_open(char source[40].\n"). case 2:fd=open(source.h> #include<sys/stat.blogspot.The Content of FILE is -----------------\n\n").count. } if(fd==-1) printf("\n\n\t\t*** Cannot OPEN the File.h> #include< mode){ // Function for Opening File int .buff.h> #include<string. switch(mode){ case 0:fd=open(source. return fd.buff[2048]. if(fd!=-1){ // Function for avscomputer.h> #include<sys/types.break. else printf("\n\n\t\t* * * The File is OPENED Successfully * * *\n\n").break. case 1:fd=open(source.h> #include<fcntl.h> void display(int fd){ //function for Displaying FILE int count.O_RDONLY).0). while((count=read(fd. } void file_read(char source[40]){ Reading File int fd.Created by Amit S #include<stdio.

fd=file_open(source.blogspot. close(fdnew).&data).buf->st_ino). } } void file_copy(char source[40]){ // Finction for Copying File int count.fdnew.0).0L. } printf("\n\n----The FILE is Copied Successfully------").buf->st_uid). printf("\nInode = %d". } } void file_status(char source[40]){ // Function for File Status int fd. /* inode */ printf("\nProtection Mode = %d".scanf("%s".Created by Amit S display(fd). close(fd). /* number of hard links */ printf("\nUser ID of Owner = %d". fdold=file_open(source.&dest). fdnew=creat(dest. char data[20].count. if((fdold!=-1)&&(fdnew!=-1)){ while((count=read(fdold. count=strlen(data).buffer. scanf("%s". close(fd).buf->st_nlink). char id[20]. printf("\n\n\nEnter the Data to write to File\n\n "). write(fd.0). /* user ID of owner */ avscomputer. file_read(dest)..sizeof(buffer)))>0){ write(fdnew.2). char dest[40]. struct stat *buf.buf->st_mode). //To read from Begining of File display(fd). close(fdold).count). fd=file_open(source.buffer. if(fd!=-1){ display(fd)."). printf("\nEnter Name of Destination File:: ").0).count). /* protection */ printf("\nHard Links = %d".. printf("\n\n\t***The Status of File is***").com . if(fd!=-1){ stat(source.buffer[2048].data. int fdold.buf). if(fdnew==-1) printf("\nCannot Creat the File. } } void file_write(char source[40]){ int fd.0666). lseek(fd.

avscomputer.buf->st_blocks).. printf("\n\t\t 8. printf("\n\n\tThe LAST character in the FILE is :: %c".Exit").c)."). printf("\n\t\t 4.Open File").buf->st_size). char s[40]. read(fd.. printf("\n\t\t 3. fd=file_open(source. /* number of blocks allocated */ //printf("\nLast Access = %d". if(val==0) printf("\n\n\t***The File is Deleted SuccessFully***").com .&c.&ch). } void file_seek(char source[40]){ int fd.buf->st_rdev). else printf("\n\n\tERROR Occured while deleting File.fstat").Created by Amit S printf("\nGroup ID of Owner = %d".&d. printf("\n\t\t\t 6. /* group ID of owner */ printf("\nDevice Type = %d". printf("\n\t Your Choice ::").buf->st_gid). close(fd). /* blocksize for filesystem I/O */ printf("\nBlocks Allocated = %d". char c.2). printf("\n\t\t 5.Delete File").Read File"). in bytes */ printf("\nBlock Size = %d".&s).-2L.buf->st_ctime). printf("\n\n\tEnter the Name of Source File:: "). /* time of last modification */ //printf("\nLast Change = %d".. } } main(){ int ch.Seek File"). lseek(fd.d). printf("\n\t\t\t 7.buf->st_atime). /* time of last change */ } } void file_delete(char source[40]){ // Function for DELETING File int val. /* time of last access */ //printf("\nLast Modification = %d".buf->st_blksize).break. if(fd!=-1){ read(fd.0). printf("\n\t\t 2. /* device type (if inode device) */ printf("\nSize(Bytes) = %d".blogspot. scanf("%d".d. /* total size. printf("\n\t\t 1. printf("\n\n\tThe FIRST character in the FILE is :: %c".2).buf->st_mtime).1).Copy File").Write to File").scanf("%s".1). val=unlink(source). switch(ch){ case 1:file_open(s. do{ printf("\n\t\tFile Management Operations").

default:printf("\n\n\tWRONG Choice.break.Open File 2.Read File 3.fstat 5.fstat 5.Seek File 8.Copy File 6./a. case 4:file_status(s).Read File 3.break. case 7:file_delete(s).break.Exit Your Choice ::1 * * * The File is OPENED Successfully * * * Enter the Name of Source File:: /root/Unix_Pro/temp_file.Write to File 4.Delete File 7.break.Delete File 7.Created by Amit S case 2:file_read(s).Seek File 8. } [root@localhost Unix_Pro]# gcc File_Manage.Copy File 6.blogspot. } }while(ch!=8).txt File Management Operations 1. exit(0).Write to File 4.").break.. case 5:file_copy(s).txt File Management Operations 1.break.out Enter the Name of Source File:: /root/Unix_Pro/temp. case 8:break.c [root@localhost Unix_Pro]# . case 3:file_write(s).Exit Your Choice ::2 * * * -------The File is OPENED Successfully * * * ----------------- The Content of FILE is avscomputer. case 6:file_seek(s).com .Open File 2..

blogspot. Thank You.Write to File 4. just doing timepass with mobile games. MurlidharRamdasRakshe Enter the Name of Source File:: /root/Unix_Pro/temp_file. I wil br veyr happy with that . Thank You.The Content of FILE is ----------------Hi how are You i am Fine Yar what are you doing dud? Nothing yar. why not.Copy File 6.Exit Your Choice ::5 Enter Name of Destination File:: /root/Unix_Pro/tempy. I wil br veyr happy with that .Seek File 8.fstat 5.Created by Amit S Hi how are You i am Fine Yar what are you doing dud? Nothing yar.Read File 3.txt * * * The File is OPENED Successfully * * * ----The FILE is Copied Successfully-----* * * The File is OPENED Successfully * * * -------. then can you come with me to see a film 'Chak De'? yes. just doing timepass with mobile games.txt File Management Operations 1. then can you come with me to see a film 'Chak De'? yes. why not. You have any paln fo the evining? .Delete File 7. MurlidharRamdasRakshe avscomputer.Open File 2. You have any paln fo the evining? No.

fstat 5.Read File 3. Each thread has its own stack. Relevant Theory / Literature Survey: (Brief Theory Expected) Threads: A thread is a single sequence stream within a process.Delete File .Write to File 4.Created by Amit S Enter the Name of Source File:: /root/Unix_Pro/tempy.txt File Management Operations 1.Seek File 8.Copy File 6. Threads are executed within a process. data section.blogspot. A thread consists of a program counter (PC). such as open files and signals. They are sometimes called lightweight processes. Threads are popular way to improve application through parallelism. threads allow multiple executions of streams. a thread can be in any of several states (Running. a register set. avscomputer. Blocked. process with one thread.Exit Your Choice ::6 ***The File is Deleted SuccessFully*** Title of Assignment: Simultaneous execution of two or more threads. In a process. and a stack space.e. OS resources also known as task.. Threads are not independent of one other like processes as a result threads shares with other threads their code section.Open File 2. Like a traditional process i. Ready or Terminated). The CPU switches rapidly back and forth among the threads giving illusion that the threads are running in parallel.

program code. If one thread is blocked. avscomputer. execute sequentially. another thread can run. they do not need to use IPC.blogspot. Disadvantage: There is no protection between threads. o They only need a stack and storage for registers for creation of threads. Differences: • • Threads are not independent of one another. o Threads do not need new address . global data.Created by Amit S Processes Vs Threads: Similarities • • • • Threads share CPU and only one thread active (running) at a time. Threads within a process. Thread can create children. o Contexts switching is fast when working with threads. Advantages of threads: o As threads can share common data. All threads can access every address in the task belonging to same process.

user-level threads usually switch faster than kernellevel threads which adds to processor efficiency. This reduces the overhead for the initial programming by the writer of the operating system. In fact. Linux primarily uses kernel-level threads. In addition. all other threads in that process will lose their timeslice. (2) Kernel-Level Threads: Since the only advantage in Linux of using user-level threads is cooperative multitasking. the kernel knows nothing about user-level threads and manages them as if they were single-threaded processes. Finally. so thread switching does not need to call operating system and to cause interrupt to the kernel. The kernel has a thread table that keeps track of all threads in the system. In this method. There are many advantages of using this method. Also. rather than via systems calls.blogspot. it cannot take advantage of any operating systems that can use symmetric multiprocessing. There are three main disadvantages to user-level threads.Created by Amit S Types of threads : (1) User-Level Threads : User-level threads implement in user-level libraries. The user can accomplish this by moving the stack point at his discretion. the kernel knows about and manages the threads. Also. . starvation can often occur if one thread takes up too much of the time-slice. One. the kernel also maintains the traditional process table to keep track of processes. Input/output blocking is not a problem as it is in user-level. The second is if one thread gets blocked. Operating Systems kernel provides system call to create and manage threads. the operating system’s code can take advantage of symmetric multiprocessing.

and they are inexpensive to represent. they require space to store. Each thread also contains a PID. etc. the SP. Each thread can be referred to individually or as a group. it is assigned a TID. Disadvantages of Threads over Multi processes • Blocking The major disadvantage if that if the kernel is single threaded. For example. • Security Since there is. for example sharing code section. parent identification. Advantages of Threads over Multiple Processes • Context Switching Threads are very inexpensive to create and destroy. If the TID for the parent is 0x00011234 and the children’s TID’s are 0x00021234 and 0x00031234. • Sharing Threads allow the sharing of a lot resources that cannot be shared in process. For . thread identification. an extensive sharing among threads there is a potential problem of security. and the threads share the parent's PID. Information about open files of I/O devices in use. and the general-purpose registers. All threads that are children of the same parent are assigned the same PID. With so little context.blogspot. It is quite possible that one thread over writes avscomputer. data section. each thread can be accessed with the address 0x00001234.Created by Amit S How the Kernel Accesses the Threads Each process contains at least one parent thread and as each thread is spawned. the PC. but they do not require space to share memory information. an application has three threads. a system call of one thread will block the whole process and CPU may be idle during the blocking period. Operating System resources like open file etc. one parent and two children. it is much faster to switch between threads.

com . Pthread_exit: This function is used to terminate the calling thread. void *(* start_routine) (void *).Created by Amit S the stack of another thread although it is very unlikely since threads are meant to cooperate on a single task.Second argument is pointer to pointer that points to return value from the thread. Arguments to be passed to the function : When a new thread is created it executes the function pointed by the function variable name. Syntax : Int pthread_join(pthread_t th . Basic thread primitives: There are various primitives that a thread system must provide. avscomputer. and gathers information about the thread's exit status. First argument is the thread for which to wait.blogspot. Usually there is no need to set the thread attributes. This identifier helps to refer to thread. Name of function : The name of the function to be started by the thread for execution. Syntax : Int pthread_create(pthread_t *thread.It waits for the thread represented in the call to finish executing. When a thread is created identifier is written into the variable to which the pointer points. It waits for the specified thread to complete. It is analogous to wait() in Unix. Pass this argument as NULL. thread_create : It is used to create a new thread. pthread_join : It is used to wait for the thread represented in the thread_join call. void *threadreturn). Syntax : Void pthread_Exit(void *retval). void *arg) Pthread_t : It is defining a thread pointer. Pthread_attr_t : It is used to set the thread attributes. pthread_attr_t *attr.

(void *) res). b).h> int A[5][5].p. NULL. NULL.&retval). int res1.h> #include<unistd.t_sub. int main(){ pthread_t t_add. NULL.m.D[5][5]. res3=pthread_join(t_mul. res2=pthread_join(t_sub. res1=pthread_join(t_add. void *Mul(void *).Created by Amit S /*Program : Multithreading*/ #include<stdio.p. void *Sub(void *).&retval).&retval). Add. (void *) res). Sub. printf("\n"). if(n==p){ pthread_create(&t_mul. pthread_create(&t_mul. (void *) res). void * .m. are \n "). (void *) res).res. } else{ printf("\n\tFor Addition and Substraction the order of Matrices Should be Same\n\n "). void accept().q. res3=pthread_join(t_mul. Mul.C[5][5]. accept().res2.q).res3. void display(int X[5][5].&retval).blogspot. if(m==p&&n==q){ pthread_create(&t_add. pthread_create(&t_sub.n).B[5][5]. void *Add(void *).t_mul. avscomputer. NULL.E[5][5]. display(B.h> #include<stdlib. printf("\n\n\tThe Entered Matrices display(A.h> #include<pthread.n.

j.j<q.j). for(i=0.m.scanf("%d". } } printf("\n\n\t\t\tThe Addition is Over").j<n.i++){ for(j=0.&n).i.i++){ for(j=0.j). } } void *Add(void *arg){ int i.j.n). printf("\n\n\tEnter The Order of Matrix A(m*n) :: ").j<n. } printf("\n\t\t\t").int b){ int i.X[i][j]).&m.scanf("%d %d".j++){ printf("\n\t\t\tB[%d][%d]==". printf("\n\t\t\t").i<m.&p.i<m. printf("\n\n\t\tEnter The Elements").i< . } void *Sub(void *arg){ int i.j++){ printf(" %d". for(i=0. for(i=0. printf("\n\n\t\tEnter The Elements"). for(i=0.j<b. sleep(1). display(C.j<n. } exit(EXIT_SUCCESS). } void accept(){ int i.&A[i][j]).i++){ for(j=0.blogspot.j++){ avscomputer.i++){ for(j=0.scanf("%d".&B[i][j]). } } } void display(int X[5][5].j.scanf("%d %d".i<p.i<a.j.i++){ for(j=0.&q). printf("\n\tIn ADDITION Function"). } } printf("\n\n\tEnter The Order of Matrix B(p*q) :: ").j++){ C[i][j]=A[i][j]+B[i][j].Created by Amit S } else printf("\n\t\tFor Multiplaication A(n) Should be Equal to B(p)").i. pthread_exit(NULL). for(i=0.j++){ printf("\n\t\t\tA[%d][%d]==".int a.

m.out Enter The Order of Matrix A(m*n) :: Enter The Elements A[0][0]==1 A[0][1]==2 A[1][0]==1 A[1][1]==3 Enter The Order of Matrix B(p*q) :: Enter The Elements B[0][0]==1 B[0][1]==3 B[1][0]==2 B[1][1]==1 The Entered Matrices are 1 1 2 3 2 2 2 2 avscomputer.q). sleep(1).i++){ for(j=0.blogspot. } } printf("\n\n\t\t\tThe Substraction is Over").com .j. } void *Mul(void *arg){ int i.m.i<m./a.j++){ E[i][j]=0. display(D. printf("\n\t\tIn SUBSTRACTION Function").k<n.j<q. pthread_exit(NULL). pthread_exit(NULL). display(E. } } } printf("\n\n\t\t\tThe Multiplaication is Over"). printf("\n\t\t\tIn MULTIPLICATION Function"). for(i=0. sleep(1).c -lpthread [root@localhost Thread]# .n). } -------------------OUTPUT-------------------[root@localhost Thread]# gcc mat.k++){ E[i][j]+=A[i][k]*B[k][j]. for(k=0.k.Created by Amit S D[i][j]=A[i][j]-B[i][j].

out Enter The Order of Matrix A(m*n) :: Enter The Elements A[0][0]==1 A[0][1]==2 A[0][2]==1 A[1][0]==2 A[1][1]==3 A[1][2]==1 Enter The Order of Matrix B(p*q) :: Enter The Elements B[0][0]==1 B[0][1]==1 B[1][0]==1 B[1][1]==1 B[2][0]==1 B[2][1]==1 2 3 3 2 .blogspot./a.Created by Amit S 1 2 3 1 In ADDITION Function In SUBSTRACTION Function In MULTIPLICATION In ADDITION Function In SUBSTRACTION Function In MULTIPLICATION In ADDITION Function In SUBSTRACTION Function In MULTIPLICATION In ADDITION Function In SUBSTRACTION Function In MULTIPLICATION Function Function Function Function The Addition is Over 2 5 3 4 The Substraction is Over 0 -1 -1 2 In In In In MULTIPLICATION MULTIPLICATION MULTIPLICATION MULTIPLICATION Function Function Function Function The Multiplaication is Over 5 5 7 6 [root@localhost Thread]# .

Created by Amit S The Entered Matrices are 1 2 1 1 1 2 3 1 1 1 1 1 For Addition and Substraction the order of Matrices Should be Same In In In In In In In In In In In In MULTIPLICATION MULTIPLICATION MULTIPLICATION MULTIPLICATION MULTIPLICATION MULTIPLICATION MULTIPLICATION MULTIPLICATION MULTIPLICATION MULTIPLICATION MULTIPLICATION MULTIPLICATION Function Function Function Function Function Function Function Function Function Function Function Function The Multiplaication is Over 4 4 6 6 Conclusion: Studied difference between threads and processes. advantages and disadvantages. creation of threads and uses of threads.blogspot. .

As it operates on behalf of the calling process. it can access the data in the processes address space. Linux transfers the execution from user space to the kernel space through system calls and the hardware interrupts.e. They can be unlinked from the kernel and removed when they are no longer needed. This makes adding new components into the kernel. The alternative to this is the micro kernel structure where the functional pieces of the kernel are broken out into units with strict communication mechanism between them. Linux Kernel Module :The Linux kernel is a monolithic kernel i. while the applications work in the lowest level where direct access to hardware and memory are prohibited. Mostly the Linux kernel modules are used avscomputer. which can be dynamically linked to the kernel even after the system bootup. rather time consuming. via the configuration process. it is one single large program where all the functional components of the kernel have access to all of its internal data structures and routines. works to the processes and related to any particular . The Linux kernel modules are piece of codes. which invokes the system call. The kernel works in the highest level (also called supervisor mode) where it has all the authority.Created by Amit S Title of Assignment: Write and insert linux kernel module. The kernel code that handles interrupts. This is the best alternative to dynamically load and unload the components of the operating system using Linux Kernel Modules.blogspot. The Kernel code executing the system call works in the context of the process. Relevant Theory / Literature Survey: (Brief Theory Expected) Linux operates in two modes--the Kernel mode (kernel space) and the User mode (user space).

Loading modules : insmod command loads the `loadable kernel modules' in the running kernel. it undoes whatever entry function did. It unregisters the functionality that the entry function registered. Every kernel module needs to include linux/module.Created by Amit S for device drivers such as network drivers or file system. When the Linux kernel discovers the need for a avscomputer. It `unregisters' the module functionality from the kernel. Init_module(): The init_module is called when the module is inserted into the kernel The module is registered to the kernel and attaches its data-structures and functionality to the kernel.Every module must have an entry function and an exit function. All modules end by calling either cleanup_module or the function you specify with the module_exit call. entry function returns and the module does nothing until the kernel wants to do something with the code that the module provides. insmod tries to link a module into the running kernel by resolving all the symbols from the kernel's exported `symbol table'. Module always begin with either the init_module or the function specified with module_init call. Modules are pieces of code that can be loaded and unloaded into the kernel upon demand. The kernel-defined external functions are also . They extend the functionality of the kernel without the need to reboot the system. When a Linux kernel module is loaded. it becomes a part of the Linux kernel as the normal kernel code and functionality and it posses the same rights and responsibilities as the kernel code. executes a bunch of instructions and terminates upon completion of those instructions.h.blogspot. it tells the kernel what functionality the module provides and sets up the kernel to run the module's functions when they're needed. This is the exit function for modules. Once it does this. Kernel modules work a bit differently. This is the entry function for modules. cleanup_module(): This module is called just before removing the module from the kernel. A program usually begins with a main() function.

It is used to insert a module into the Linux Kernel. it opens the IPC channel to the kernel and uses it for transferring messages (request for loading modules).It uses the sys_create_module to allocate kernel memory to hold module. insmod calls the initialization function of the concerned module i. At the time of booting. to and from the kernel.e. While removing modules. Insmod : The insmod depends on some critical system calls to load the module to the kernel."i"). The cleanup_module function of the concerned module is called to freeup the kernel resources it has allocated.blogspot."b"). the kerneld calls modprobe and insmod to load the required module. static int s_module(void) { int c=0.Created by Amit S module.h> #include <linux/kernel. #include <linux/module. These system are in kernel/module.h> static int a. avscomputer. While loading the module. the module datastructure is marked DELETED and it is unlinked from the kernel and unlisted from the list of kernel modules. The reference list of the modules on which it is dependent is modified and dependency is released. MODULE_PARM(a. It then calls the sys_init_module system call to copy the relocatable object code of the module to the kernel space.c. Unloading modules : The modules can be unloaded using rmmod command. The kernel memory allocated to the concerned module is deallocated and returned to the kernel memory spool. The demand loadable kernel modules are usually located at /lib/module/ directory. After the successful execution of the cleanup_module. And soon after this. It uses get_kernel_syms system call to get the kernel symbol table in order to link the module. rmmod ensures the restriction that the modules are not in use and they are not referred by any other module or the part of the kernel. the kernel requests to the kernel daemon to load the appropriate module. init_module.h> #include <linux/ . The kernel daemon is the process having exclusive superuser privileges. MODULE_PARM(b.b.

} module_init(s_module). MODULE_LICENSE("GPL").com .20-8 avscomputer.c:62: void value not ignored as it ought to be file.Created by Amit S printk("<1>hello world\n"). c=2+3.c). [root@localhost root]# vi raj.20 while this kernel is version 2.4.ko was compiled for kernel version 2.c [root@localhost root]# insmod -f raj.c -o file file. return 0.c: In function `read1': file. } static void e_module(void) { printk("<1>good bye \n"). printk("sum is %d\n".blogspot.ko Warning: kernel-module version mismatch raj.o abhi.c [root@localhost root]# make file gcc -DMODULE -D__KERNEL__ -isystem /lib/modules/`uname -r`/build/include file. module_exit(e_module).4.c: In function `write1': [root@localhost root]# make gcc -DMODULE -D__KERNEL__ -isystem /lib/modules/`uname -r`/build/include -c -o abhi.

tux.ko loaded.ko ide-cd cdrom soundcore parport_pc lp parport autofs ipt_REJECT iptable_filter ip_tables keybdev mousedev hid input usb-uhci ehci-hcd usbcore ext3 jbd Size Used by Tainted: GF 856 0 (unused) 35708 0 (autoclean) 33728 0 (autoclean) [ide-cd] 6404 0 (autoclean) 19076 1 (autoclean) 8996 0 (autoclean) 37056 1 (autoclean) [parport_pc lp] 13268 0 (autoclean) (unused) 3928 6 (autoclean) 2412 1 (autoclean) 15096 2 [ipt_REJECT iptable_filter] 2944 0 (unused) 5492 1 22148 0 (unused) 5856 0 [keybdev mousedev hid] 26348 0 (unused) 19976 0 (unused) 78784 1 [hid usb-uhci ehci-hcd] 70784 2 51892 2 [ext3] [root@localhost root]# mkdir -p/lib/modules/$(uname -r)/kernel/drivers/raj .org/lkml/#export-tainted for information about tainted modules Module raj.Created by Amit S Warning: loading raj.blogspot. with warnings [root@localhost root]# lsmod Module raj.ko will taint the kernel: forced load See http://www.

4.2.redhat.4.2.2 20030222 (Red Hat Linux 3.2.redhat.ko [root@localhost root]# dmesg Linux version 2.devel.ko [root@localhost root]# vi /etc/modules [root@localhost root]# reboot [root@localhost root]# insmod -f raj.2 20030222 (Red Hat Linux 3.2-5)) #1 Thu Mar 13 17:54:28 EST 2003 BIOS-provided physical RAM map: hello world [root@localhost root]# rmmod raj.2.c (gcc version (gcc version 3.devel.blogspot.20-8 (bhcompile@porky.2-5)) #1 Thu Mar 13 17:54:28 EST 2003 BIOS-provided physical RAM map: hello world sum is 5 good bye Conclusion: Studied the different commands used in loading and unloading of kernel module.ko [root@localhost root]# dmesg dmesg Linux version . avscomputer.20-8 (bhcompile@porky.Created by Amit S [root@localhost root]#cp raj.

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.