+ All Categories

Unix lab

Date post: 12-Jan-2017
Category:
Upload: vivek-kumar-sinha
View: 11 times
Download: 0 times
Share this document with a friend
31
Shri Rawatpura Sarkar Institute Of Technology –II New Raipur Department of Computer science and Engineering Lab Manual UNIX and Shell Programming Lab
Transcript
Page 1: Unix lab

Shri Rawatpura Sarkar Institute Of Technology –II New Raipur

Department of Computer science and Engineering

Lab Manual

UNIX and Shell Programming Lab

Page 2: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

Experiment 1

A.Write a shell script that accepts a file name, starting and ending line numbers as arguments and displays all the lines between the given line numbers.

Aim: ToWrite a shell script that accepts a file name, starting and ending line numbers as arguments and displays all the lines between the given line numbers.

Script:$ awk ‘NR<2 || NR> 4 {print $0}’ 5 lines.dat

I/P: line1line2line3line4line5

O/P: line1 line5

B. Write a shell script that deletes all lines containing a specified word in one or more files supplied as arguments to it.

Aim: To write a shell script that deletes all lines containing a specified word in one or more files supplied as arguments to it.

Script:cleari=1while [ $i -le $# ]dogrep -v Unix $i > $idone

Output:$ sh 1b.sh test1the contents before deletingtest1hello hello

SRIT ,RAIPUR Page 2

Page 3: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

bangaloremysore cityenter the word to be deletedcityafter deletinghello hello Bangalore

$ sh 1b.shno argument passed

SRIT ,RAIPUR Page 3

Page 4: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

Experiment 2

A. Write a shell script that displays a list of all the files in the current directory to which the user has read, write and execute permissions.

Aim: To write a shell script that displays a list of all the files in the current directory to which the user has read, write and execute permissions.

Script:echo "enter the directory name"read dirif [ -d $dir ]then cd $dirls > fexec < fwhile read linedoif [ -f $line ]thenif [ -r $line -a -w $line -a -x $line ]thenecho "$line has all permissions"elseecho "files not having all permissions"fifidone

fi

B. Write a shell script that receives any number of file names as arguments checks if every argument supplied is a file or a directory and reports accordingly. Whenever the argument is a file, the number of lines on it is also reported

Aim: To write a shell script that receives any number of file names as arguments checks if every argument supplied is a file or a directory

Script:

SRIT ,RAIPUR Page 4

Page 5: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

for x in $*doif [ -f $x ]thenecho " $x is a file "echo " no of lines in the file are "wc -l $xelif [ -d $x ]thenecho " $x is a directory "elseecho " enter valid filename or directory name "fi

done

SRIT ,RAIPUR Page 5

Page 6: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

Experiment 3A. Write a shell script to list all of the directory files in a directory.

Script:# !/bin/bashecho"enter directory name"read dirif[ -d $dir]thenecho"list of files in the directory"ls $direlse echo"enter proper directory name"

fi Output: Enter directory name Atri List of all files in the directoty CSE.txt ECE.txt

B. Write a shell script to find factorial of a given integer. Script:

# !/bin/bashecho "enter a number"read numfact=1while [ $num -ge 1 ]dofact=`expr $fact \* $num`let num--done

echo "factorial of $n is $fact"

Output: Enter a number

SRIT ,RAIPUR Page 6

Page 7: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

5Factorial of 5 is 120

. Experiment-4A. Write an awk script to count the number of lines in a file that do not contain vowels. . B. Write an awk script to find the number of characters, words and lines in a file.

Aim : To write an awk script to find the number of characters, words and lines in a file.

Script:BEGIN{print "record.\t characters \t words"}#BODY section{len=length($0)total_len+=lenprint(NR,":\t",len,":\t",NF,$0)words+=NF}

END{print("\n total")print("characters :\t" total len)print("lines :\t" NR)}

10. Write a c program that makes a copy of a file using standard I/O and system calls

#include <unistd.h> #include <fcntl.h>int main(int argc, char *argv[]){int fd1, fd2;char buffer[100];long int n1;if(((fd1 = open(argv[1], O_RDONLY)) == -1) ||((fd2 = open(argv[2], O_CREAT|O_WRONLY|O_TRUNC,0700)) == -1)){perror("file problem ");exit(1);}while((n1=read(fd1, buffer, 100)) > 0)if(write(fd2, buffer, n1) != n1){

SRIT ,RAIPUR Page 7

Page 8: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

perror("writing problem ");exit(3);}// Case of an error exit from the loopif(n1 == -1){perror("Reading problem ");exit(2);}close(fd2);exit(0);}

SRIT ,RAIPUR Page 8

Page 9: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

Experiment-5

A. Write a shell script that accepts a list of file names as its arguments, counts and reports the occurrence of each word that is present in the first argument file on other argument files.

Aim : To write a shell script that accepts a list of file names as its arguments, counts and reports the occurrence of each word that is present in the first argument file on other argument files.

Script:if [ $# -ne 2 ]thenecho "Error : Invalid number of arguments."exitfistr=`cat $1 | tr '\n' ' '`for a in $strdoecho "Word = $a, Count = `grep -c "$a" $2`"done

Output :$ cat testhello ATRI$ cat test1hello ATRIhello ATRIhello$ sh 1.sh test test1Word = hello, Count = 3Word = ATRI, Count = 2

SRIT ,RAIPUR Page 9

Page 10: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

Experiment-6

A. Implement in C the following UNIX commands using System calls A. cat B. ls C. mv

AIM: Implement in C the cat Unix command using system calls

#include<fcntl.h>#include<sys/stat.h>#define BUFSIZE 1int main(int argc, char **argv){ int fd1; int n; char buf; fd1=open(argv[1],O_RDONLY); printf("Welcome to ATRI\n"); while((n=read(fd1,&buf,1))>0) { printf("%c",buf);/* or write(1,&buf,1); */ } return (0);}

AIM: Implement in C the following ls Unix command using system calls Algorithm:

1. Start.2. open directory using opendir( ) system call.3. read the directory using readdir( ) system call.4. print dp.name and dp.inode .5. repeat above step until end of directory.6. End

SRIT ,RAIPUR Page 10

Page 11: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

#include <sys/types.h>#include <sys/dir.h>#include <sys/param.h>#include <stdio.h> #define FALSE 0#define TRUE 1 extern int alphasort(); char pathname[MAXPATHLEN]; main() { int count,i;struct dirent **files;int file_select(); if (getwd(pathname) == NULL ){ printf("Error getting pathn");exit(0);}printf("Current Working Directory = %sn",pathname);count = scandir(pathname, &files, file_select, alphasort); if (count <= 0){ printf("No files in this directoryn");exit(0);}printf("Number of files = %dn",count);for (i=1;i<count+1;++i)

printf("%s \n",files[i-1]->d_name);}

int file_select(struct direct *entry){if ((strcmp(entry->d_name, ".") == 0) ||(strcmp(entry->d_name, "..") == 0)) return (FALSE);elsereturn (TRUE);

SRIT ,RAIPUR Page 11

Page 12: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

}

B. AIM: Implement in C the Unix command mv using system calls Algorithm:

1. Start2. open an existed file and one new open file using open()system call3. read the contents from existed file using read( ) systemcall4. write these contents into new file using write systemcall using write( ) system call5. repeat above 2 steps until eof6. close 2 file using fclose( ) system call7. delete existed file using using unlink( ) system8. End.

Program:#include<fcntl.h>#include<stdio.h>#include<unistd.h>#include<sys/stat.h>int main(int argc, char **argv){ int fd1,fd2; int n,count=0; fd1=open(argv[1],O_RDONLY);fd2=creat(argv[2],S_IWUSR);rename(fd1,fd2);unlink(argv[1]);printf(“ file is copied “);return (0);}

SRIT ,RAIPUR Page 12

Page 13: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

Experiment-7

A. Write a program that takes one or more file/directory names as command line input and reports the following information on the file.

A. File type. B. Number of links. C. Time of last access. D. Read, Write and Execute permissions.#include<stdio.h>main(){FILE *stream;int buffer_character;stream=fopen(“test”,”r”);if(stream==(FILE*)0){fprintf(stderr,”Error opening file(printed to standard error)\n”);fclose(stream);exit(1);}}if(fclose(stream))==EOF){fprintf(stderr,”Error closing stream.(printed to standard error)\n);exit(1);}return();

SRIT ,RAIPUR Page 13

Page 14: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

Experiment-8

A. . Write a C program to list for every file in a directory, its inode number and file name. The Dirent structure contains the inode number and the name. The maximum length of a filename component is NAME_MAX, which is a system-dependent value. opendir returns a pointer to a structure called DIR, analogous to FILE, which is used by readdir and closedir. This information is collected into a file called dirent.h.

#define NAME_MAX 14 /* longest filename component; */

/* system-dependent */

typedef struct { /* portable directory entry */

long ino; /* inode number */

char name[NAME_MAX+1]; /* name + '\0' terminator */

} Dirent;

typedef struct { /* minimal DIR: no buffering, etc. */

int fd; /* file descriptor for the directory */

Dirent d; /* the directory entry */

} DIR;

DIR *opendir(char *dirname);

Dirent *readdir(DIR *dfd);

void closedir(DIR *dfd);

SRIT ,RAIPUR Page 14

Page 15: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

The system call stat takes a filename and returns all of the information in the inode for that file, or -1 if there is an error. That is,

char *name;

struct stat stbuf;

int stat(char *, struct stat *);

stat(name, &stbuf);

fills the structure stbuf with the inode information for the file name. The structure describing the value returned by stat is in <sys/stat.h>, and typically looks like this:

struct stat /* inode information returned by stat */

{

dev_t st_dev; /* device of inode */

ino_t st_ino; /* inode number */

short st_mode; /* mode bits */

short st_nlink; /* number of links to file */

short st_uid; /* owners user id */

short st_gid; /* owners group id */

dev_t st_rdev; /* for special files */

off_t st_size; /* file size in characters */

time_t st_atime; /* time last accessed */

time_t st_mtime; /* time last modified */

time_t st_ctime; /* time originally created */

};

Most of these values are explained by the comment fields. The types like dev_t and ino_t are defined in<sys/types.h>, which must be included too.

SRIT ,RAIPUR Page 15

Page 16: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

The st_mode entry contains a set of flags describing the file. The flag definitions are also included in<sys/types.h>; we need only the part that deals with file type:

#define S_IFMT 0160000 /* type of file: */

#define S_IFDIR 0040000 /* directory */

#define S_IFCHR 0020000 /* character special */

#define S_IFBLK 0060000 /* block special */

#define S_IFREG 0010000 /* regular */

/* ... */

Now we are ready to write the program fsize. If the mode obtained from stat indicates that a file is not a directory, then the size is at hand and can be printed directly. If the name is a directory, however, then we have to process that directory one file at a time; it may in turn contain sub-directories, so the process is recursive.

The main routine deals with command-line arguments; it hands each argument to the function fsize.

#include <stdio.h>

#include <string.h>

#include "syscalls.h"

#include <fcntl.h> /* flags for read and write */

#include <sys/types.h> /* typedefs */

#include <sys/stat.h> /* structure returned by stat */

#include "dirent.h"

void fsize(char *)

/* print file name */

main(int argc, char **argv)

{

SRIT ,RAIPUR Page 16

Page 17: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

if (argc == 1) /* default: current directory */

fsize(".");

else

while (--argc > 0)

fsize(*++argv);

return 0;

}

The function fsize prints the size of the file. If the file is a directory, however, fsize first calls dirwalk to handle all the files in it. Note how the flag names S_IFMT and S_IFDIR are used to decide if the file is a directory. Parenthesization matters, because the precedence of & is lower than that of ==.

int stat(char *, struct stat *);

void dirwalk(char *, void (*fcn)(char *));

/* fsize: print the name of file "name" */

void fsize(char *name)

{

struct stat stbuf;

if (stat(name, &stbuf) == -1) {

fprintf(stderr, "fsize: can't access %s\n", name);

return;

}

if ((stbuf.st_mode & S_IFMT) == S_IFDIR)

dirwalk(name, fsize);

printf("%8ld %s\n", stbuf.st_size, name);

SRIT ,RAIPUR Page 17

Page 18: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

}

The function dirwalk is a general routine that applies a function to each file in a directory. It opens the directory, loops through the files in it, calling the function on each, then closes the directory and returns. Since fsize calls dirwalk on each directory, the two functions call each other recursively.

#define MAX_PATH 1024

/* dirwalk: apply fcn to all files in dir */

void dirwalk(char *dir, void (*fcn)(char *))

{

char name[MAX_PATH];

Dirent *dp;

DIR *dfd;

if ((dfd = opendir(dir)) == NULL) {

fprintf(stderr, "dirwalk: can't open %s\n", dir);

return;

}

while ((dp = readdir(dfd)) != NULL) {

if (strcmp(dp->name, ".") == 0

|| strcmp(dp->name, ".."))

continue; /* skip self and parent */

if (strlen(dir)+strlen(dp->name)+2 > sizeof(name))

fprintf(stderr, "dirwalk: name %s %s too long\n",

dir, dp->name);

else {

SRIT ,RAIPUR Page 18

Page 19: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

sprintf(name, "%s/%s", dir, dp->name);

(*fcn)(name);

}

}

closedir(dfd);

}

Each call to readdir returns a pointer to information for the next file, or NULL when there are no files left. Each directory always contains entries for itself, called ".", and its parent, ".."; these must be skipped, or the program will loop forever.

Down to this last level, the code is independent of how directories are formatted. The next step is to present minimal versions of opendir, readdir, and closedir for a specific system. The following routines are for Version 7 and System V UNIX systems; they use the directory information in the header<sys/dir.h>, which looks like this:

#ifndef DIRSIZ

#define DIRSIZ 14

#endif

struct direct { /* directory entry */

ino_t d_ino; /* inode number */

char d_name[DIRSIZ]; /* long name does not have '\0' */

};

Some versions of the system permit much longer names and have a more complicated directory structure.

The type ino_t is a typedef that describes the index into the inode list. It happens to be unsigned short on the systems we use regularly, but this is not the sort of information to embed in a program; it might be different on a different system, so the typedef is better. A complete set of ``system'' types is found in <sys/types.h>.

opendir opens the directory, verifies that the file is a directory (this time by the system call fstat, which is like stat except that it applies to a file descriptor), allocates a directory structure, and records the information:

SRIT ,RAIPUR Page 19

Page 20: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

int fstat(int fd, struct stat *);

/* opendir: open a directory for readdir calls */

DIR *opendir(char *dirname)

{

int fd;

struct stat stbuf;

DIR *dp;

if ((fd = open(dirname, O_RDONLY, 0)) == -1

|| fstat(fd, &stbuf) == -1

|| (stbuf.st_mode & S_IFMT) != S_IFDIR

|| (dp = (DIR *) malloc(sizeof(DIR))) == NULL)

return NULL;

dp->fd = fd;

return dp;

}

closedir closes the directory file and frees the space:

/* closedir: close directory opened by opendir */

void closedir(DIR *dp)

{

if (dp) {

close(dp->fd);

free(dp);

}

SRIT ,RAIPUR Page 20

Page 21: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

}

Finally, readdir uses read to read each directory entry. If a directory slot is not currently in use (because a file has been removed), the inode number is zero, and this position is skipped. Otherwise, the inode number and name are placed in a static structure and a pointer to that is returned to the user. Each call overwrites the information from the previous one.

#include <sys/dir.h> /* local directory structure */

/* readdir: read directory entries in sequence */

Dirent *readdir(DIR *dp)

{

struct direct dirbuf; /* local directory structure */

static Dirent d; /* return: portable structure */

while (read(dp->fd, (char *) &dirbuf, sizeof(dirbuf))

== sizeof(dirbuf)) {

if (dirbuf.d_ino == 0) /* slot not in use */

continue;

d.ino = dirbuf.d_ino;

strncpy(d.name, dirbuf.d_name, DIRSIZ);

d.name[DIRSIZ] = '\0'; /* ensure termination */

return &d;

}

return NULL;

}

B. . Write a C program that demonstrates redirection of standard output to a file.Ex: ls > f1.

SRIT ,RAIPUR Page 21

Page 22: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

Description:An Inode number points to an Inode. An Inode is a data structure that stores the following

information about a file : Size of file Device ID

User ID of the file

Group ID of the file

The file mode information and access privileges for owner, group and others

File protection flags

The timestamps for file creation, modification etc

link counter to determine the number of hard links

Pointers to the blocks storing file’s contents

SRIT ,RAIPUR Page 22

Page 23: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

Experiment -9

A. Write a C program to create a child process and allow the parent to display “parent” and the child to display “child” on the screen.

#include<stdio.h>#include<string.h>main(){ int childpid; if (( childpid=fork())<0) { printf("cannot fork"); } else if(childpid >0) {

}else printf(“Child process”); }

SRIT ,RAIPUR Page 23

Page 24: Unix lab

Shri Rawatpura Sarkar Institute Of Technology -II

Experiment-10A. . Write a C program to create a Zombie process.

If child terminates before the parent process then parent process with out child is called zombie process

#include<stdio.h>#include<string.h>main(){ int childpid; if (( childpid=fork())<0) { printf("cannot fork"); } else if(childpid >0) { Printf(“child process”); exit(0);

SRIT ,RAIPUR Page 24


Recommended