+ All Categories
Home > Documents > Ex No 1 -4

Ex No 1 -4

Date post: 14-Nov-2014
Category:
Upload: api-3760405
View: 119 times
Download: 4 times
Share this document with a friend
Popular Tags:
58
Ex.No:1 STUDY OF UNIX COMMANDS DATE: AIM: To study the basics of Unix Operating System, commands and vi editor. Operating System: OS is system software and it is defined as an organized collection of software consisting of procedures for operating a computer. It provides an environment for execution of programs and acts as an interface between the user and the hardware of the computer system. Operating System interacts with the user in two ways. 1. Operating system commands enables user to interact directly with the operating system. 2. Operating system calls provides an interface to a running program and the program and the operating system. System calls in UNIX are written in C. HISTORY OF UNIX Ken Thompson of AT&T Bell Laboratories designed UNIX in late 1960s. Two versions of UNIX that emerged are AT&T UNIX and BSD UNIX. In 1989, AT&T and Sun Microsystems joined together and developed System V release 4(SVR4). Two of the main standards mainly in use are POSIX (Portable Operating system Interface) and X/Open standard. In 1988, MIT formed Xconsortium X/Open developed vendor-neutral Xwindow system. The UNIX Operating System 1
Transcript
Page 1: Ex No 1 -4

Ex.No:1 STUDY OF UNIX COMMANDSDATE:

AIM:

To study the basics of Unix Operating System, commands and vi editor.

Operating System:

OS is system software and it is defined as an organized collection of software consisting of procedures for operating a computer. It provides an environment for execution of programs and acts as an interface between the user and the hardware of the computer system.

Operating System interacts with the user in two ways.

1. Operating system commands enables user to interact directly with the operating system.

2. Operating system calls provides an interface to a running program and the program and the operating system. System calls in UNIX are written in C.

HISTORY OF UNIX

Ken Thompson of AT&T Bell Laboratories designed UNIX in late 1960s. Two versions of UNIX that emerged are AT&T UNIX and BSD UNIX. In 1989, AT&T and Sun Microsystems joined together and developed System V

release 4(SVR4). Two of the main standards mainly in use are POSIX (Portable Operating system

Interface) and X/Open standard. In 1988, MIT formed Xconsortium X/Open developed vendor-neutral Xwindow system.

The UNIX Operating System

UNIX is a time sharing operating system (OS), which consists of kernel file system, shell and a collection of tools and utilities.

Features of UNIX Multi-user, multitasking, time-sharing. Portability Modularity File Structure Security Strong network support and advanced graphics.

LINUX:

An open-source UNIX-like operating system.

1

Page 2: Ex No 1 -4

Initially created by Linus Torvalds for PC architecture. Developer community world-wide contribute to its enhancement and growth.

UNIX System Architecture:

USER

USER USER

UNIX is a layered operating system.

Layer 1 : This is the inner most layer called hardware that provides services for the OS.Layer 2 : The second layer is kernel which directly makes interface with the hardware system.

Actions:

Provides mechanism for creating and deleting processes. Provides processor scheduling, memory and I/O management. Does inter-process communication.

Layer 3 : The utilities and other application programs form the third layer.

A utility program that comes with the UNIX system. Features of the shell are,

1. Interactive processing.2. Background Processing3. I/O redirection.4. Pipes5. Shell Scripts6. Shell variables

2

sh

Shell

Wc sort

Vi who ….

Kernel

hardware

shell

shell

ed

a.out

sh

Page 3: Ex No 1 -4

7. Programming Constructs

Layer 4 : The fourth layer is the one with which the user actually interacts.

The User Perspective:

From the users viewpoint the following aspects of UNIX will be highlighted;

1. File system2. Processing environment.3. Building block primitives.

1. File System :

The main features of the UNIX file system are:

1. Hierarchical structure.2. Consistent treatment of file data.3. Create and delete files.4. Dynamic growth of files.5. Protection of file data.6. Peripheral devices as file.

Typical structure of UNIX file system is:

1. /dev- Contains the devices files of all the hardware devices.2. /etc- Contains those utilities mostly used by the system administrator.3. /tmp- It is used by some UNIX utilities (e.g. VI) as well as by user to store

temporary files.4. /usr- Contains system files and executables.5. /usr/src- Location of source code if one is stored.6. /usr/bin- Contains commands which a user can execute.7. /home- Place holder foe home directory of various user accounts.

File permissions can be set 3 classes of users:

File OwnerFile Owner’s groupOthers

Read(r), Write (w), Execute(X) permissions can be set for each file.

2.Processing Environment:

A process is a program in execution.

3

Page 4: Ex No 1 -4

Several processes can be executed simultaneously in a Unix system. A process is generally created using the fork() system call. The process that invokes the fork() system call is the parent process, and the newly created process is called the child process.

3.Building Block Primitives :

a. Redirection I/O:Both the standard input and output can be re-directed from/into files.

$ls > output

Here the output from the ls command gets written into the file output.

b. Pipes:A pipe is a mechanism that allows a stream of data to be passed between the read

and write process.

$grep they x.c.y.z.c|wc-1

counts the number of lines in files x.c,y.c and z.c that contain the word ‘they’; the output from grep is ‘piped’ directly as input to wc.

OPERATING SYSTEM SERVICES

1. Kernel: It performs, control of execution of processes. Scheduling of processes. Memory

management, file system service, controlled access to peripherals.

2. Hardware Transparency : Two modes used here, user mode and kernel mode.

3. Interrupts and Exceptions : Interrupt: It is a signal by which priorities and instruction scheduling sequence

can be controlled.

Exception: It is an unexpected event like reference to an illegitimate address caused by events external to a process.

4. Processor execution levels : Based on priority level of an interrupt the kernel masks certain interrupts in order

that a critical process may proceed without error.The priority levels in descending order are:

4

Page 5: Ex No 1 -4

1. Machine error2. Clock3. Disk4. Network Devices5. Terminals6. Software int7. errupts

5. Memory Management : The concept of a virtual machine is central to memory management under UNIX.

Unix Commands:

General Commands:

1. date : This tells the current date and time.

$dateThu Oct 15 09:34:50 PST 2006

2. Who : Gives the details of the users who have logged in to the system.

$whoabc tty0 oct 15 11:17xyz tty4 oct 15 11:30

3. who am i : gives the details regarding the login time and the system’s name for the connection being used.

$who am iuser1 ttya Oct 15 12:20

4. man : It displays the manual page of our terminal with the command ‘man’ command name$man who

5. head and tail : ‘Head’ is used to display the initial part of the text file. And ‘tail’ is used to display the last part of the text file.

$head [-count][file name]$tail [-count][file name]

6. pwd : It displays full path name for the current directory we are working in.

$pwd

5

Page 6: Ex No 1 -4

/usr/temp

7. ls : It displays the list of files in the current working directory.

$ls$ls –l = lists files in the long format$ls –t = lists in order of the last modification time$ls –a = lists all entries, including the hidden files$ls –d = lists directory file instead of its contents$ls –p = puts a slash after each directory$ls –u = lists in order of last access time

8. mkdir : It is used to create a new directory.

$mkdir directory name

9. cd : It is used to change from the working directory to any other directory specified.

$cd = changes to home directory$cd.. = changes to parent directory$cd/ = changes to root directory$cd dir1 = changes to directory dir1

10. rmdir : It is used to remove the directory specified in the command line.

$rmdir directory name

11. cat : This command helps us to list the contents of a file we specify.

$cat [option..][file..]

12. cp : This command is used to create duplicate copies of ordinary files.

$cp file target$ cp file1 file2 [file1 is copied to file2]

13. mv : This command is used to rename and move ordinary and directory.

$mv file1 file2$mv direcory1 directory2

14. ln : This is used to link file.

6

Page 7: Ex No 1 -4

$ln file1 [file2..] target

15. rm : This command is used to remove one or more files from a directory. This can be used to delete all files as well as directory.

$rm [option..] file

16. chmod : Changes the access permissions of a file or directory.

$chmod mode file$chmod [who][+/-/=][permission…]file

who = a-all users g-group o-others u-user

[+/-/=] = + - add - - remove

= - assigns

[Permission] = r – readw – writex – execute

mode = mode in absolute format is based on octal numbers representing the three kinds of access permissions.

4 read2 write1 execute

Ex. $chmod 754 prog1

17. Chown : change owner ID of the files or directories Owner maybe decimal user ID or a login name found in the file/etc/password. This utility is governed by the chown kernel authorization. If it is not granted Ownership can be only changed by the root.

Ex. $chown tutor test

18. Wc : counts and displays the lines, words and characters in the files specified.

$wc [option…] filename$wc –l display the number of lines$wc –w display the number of words

7

Page 8: Ex No 1 -4

$wc –c display the number of characters

ex: $wc prog2 3 9 60 prog2

19. grep : searches the file for pattern

$grep[option..]pattern[file..]

display the lines containing the pattern on the standard on the standard output

$grep –c report only the number of matching lines.$grep –l list only the names of files containing pattern.$grep –v display all lines except those containing pattern.

Ex: grep –c “the” prog2

20. Cut : cuts out selected fields of each line of a file

$cut –first[-d char][file1 file2…]-d = it is delimiter, default is tab.

Ex: cut f1,3 –d”w”prog2

21. Paste : merges the corresponding lines of the given files.

$paste –d file1 file2option –d allows replacing tab character by one or more alternate characters.

Ex: paste prog1 prog2

22. Sort : arrange lines in alphabetic or numeric order.

$sort [option] fileoption –d dictionary order option –n arithmetic orderoption –r reverse order

Ex: $ls –l | sort –n

THE VI EDITOR

The vi editor is a line oriented editor and it is not very easy to use. But it is simple and u can learn enough commands to use it for editing your java programs.

Command mode and edit mode :

8

Page 9: Ex No 1 -4

In vi, you need to shift from command mode to edit mode and back again.

You need to be in the command mode to move the cursor around from one place in the text to another.

Esc-shift to command mode

You need to be in edit mode to input or change text. You automatically shift to edit mode when you give a command that affects text. You need to hit Esc to get out of edit mode or whatever else you type will also be taken as input.

i Insert text before a charactera add text after a characterI insert text at the beginning of a lineA insert text at the end of a linex delete the current characterX delete the previous charactero open a new blank line after the current lineO Open a new blank line before the current line dd delete the current linecc change the current liner replace one characterR replace several characterss substitute new characters for 1 old one

File Access Commands :

You need some way to open an existing file, to save your work, to save and exit, and to abandon an attempt to edit a file without making any changes(just in case you really mess up). Precede these with an Esc.

ZZ or :wq Save the edited file and exit from the editor:w Save the edited file and stay in the editor:q Quit the editor:q! Quit the editor under any conditions

RESULT:

Thus the basics of UNIX operating system, commands and vi editors have been studied successfully.

9

Page 10: Ex No 1 -4

EXNO:2 STUDY OF SHELL PROGRAMSDATE:

AIM:

TO study and perform some shell programming utilities like:a) To develop menu driven command r.b) Outline.c) Finding the number is even or odd ,sum of digits, prime or not factorial of a

number and Armstrong number.d) Finding the duration of a user’s login time.e) Clean up routine.f) Calculator.

THEORY:

SHELL:

A utility program that comes with the UNIX system. Shell is an interactive command interpreter. It accepts commands that are entered

at shell prompt and execute them. A user communicates with the system using shell.

Shell that are commonly available in the UNIX system environment are:Bourne shell(bin/sh):

The original shell provided on AT&T based systems developed by Stephen bourne bell laboratories. It provides a UNIX system command interpreter and supports a programmable interface to develop shell programs or scripts as they are commonly called.

C shell:The shell developed at the Bekly software division by Bill joy and is

provided on BSD-based systems. This shell was referred as the California shell, which was shortened to just the C shell. It was considered an improvement over bourne shell because offered interactive features such as a commonstack and aliasing.

10

Page 11: Ex No 1 -4

Bash shell:Bourne- again shell bash is an sh-compatible command language

interpreter that executes commands read from standard input or from a file. Bash also incorporates useful feartures from korn and C shells.

FEAURES OF SHELL:

Interactive processing. Background processing . I/O redirection. Pipes. Shell scripts. Shell variables. Programming constructs.

SHELL FUNCTIONS:

Program execution. File name substitution using meta characters. I/O redirection. Pipeline hook-ups. Environmental control. Interpretive programming language.

SHELL VARIABLES:

Positional parameters:Positional parameters ( designated $1,$2,$3…….$9) acquire their values from position of at the command line.

Special parameters:Symbol Meaning

$# the number of positional parameters while invokingthe shell script.

$- shell options.$? Exit status of the last executed command.$$ the process number(PID) of the current shell.$! The process number of last background command.$0 The name of command being executed.$* The list of positional parameters.$@ Same as $*. Except when enclosed in double quotes.

11

Page 12: Ex No 1 -4

$@ Same as $*. Except when enclosed in double quotes.

Named variables:

A named variable is a user defined variable that can be assigned a value with in a shell program. The value of a named variable can be retrieved by preceding the variable name with a ‘$’ sign.Example:

$ xvar=Hai$ echo $xvarHai .

COMMANDS IN SHELL:

1. READUsed to get input(data from user) from keyboard and store (data) to variable.

Syntax:Read variable1,variable2,……variable N.

2. ECHOEcho command is used to display text or value of variable.

Syntax:Echo[options] [string, variables..]

Displays text or variables value on screen.

3. TESTFunction provided by bash called test which returns a true or false value depending on the result of the tested expression. Its syntax is:

Test expression

It can also be implied as follows:

[expression]

The tests below are test conditions provided by the shell:-b file - true if the file exists and is block special file.-c file - true if the file exists and is character special

File.-d file - true if the file exists and is a directory.-e file - true if the exists.

12

Page 13: Ex No 1 -4

-f file - true if the file exists and is regular file.-r file - true if the file exists and is a readable.-w file - true if the file exists and is writeable.String 1 =string 2 - true if the strings are equal.String 1!= string 2- true if the strings are not equal.

LOOPING IN SHELL:a) THE FOR LOOP:

The general form of for loop in bourne shell is :For variable-name in value1,value2…….

Do<commands>

Done

The case statement:The general form of case statement in bourne shell is :

Choice 1) commands;;Choice 2) commands;;………….………….………….esac

b)The while loop :The general form of while loop is

While control command

Do<commands>

Done

c)The until loop:Until control command Do

<commands>Done

d)The if statement:If control commandThen

<commands>Fi

e)If…..then…..else statement:

13

Page 14: Ex No 1 -4

If control commandThen

<commands>Else

<commands>Fi

f)If then……elif then ……else statement:

If control comand1Then

<commands>Elif control command2

Then<commands>

Else<commands>

Fi

14

Page 15: Ex No 1 -4

PROGRAM 1:

AIM: To code a shell script to display message.

PROGRAM:

#program to display message.

#This is my first shell programclearecho "welcome"

OUTPUT:

$sh display.shwelcome$

RESULT: Thus a message is displayed using shell script.

15

Page 16: Ex No 1 -4

PROGRAM 2:

AIM: To code a shell script to determine whether given number is even or odd:

PROGRAM:

#program to determine whether given number is even or odd.

echo "enter the number"read x

if [ ` expr $x \% 2 ` -eq 0 ]then

echo "$x is even number"else

echo "$x is odd number"fi

OUTPUT:

$sh evenorodd.shenter the number 33 is odd number$sh evenorodd.shenter the number 66 is even number$

RESULT: Thus a given numbered is checked whether it is even or odd by using shell script.

16

Page 17: Ex No 1 -4

PROGRAM 3:

AIM:To code a shell script to determine the sum of digits of given number.

PROGRAM:

# program to determine the sum of digits of given number.

echo "enter the number"read xc=0a=0while [ $x -ne 0 ]do

c=` expr $x \% 10 `a=` expr $a \+ $c `x=` expr $x \/ 10 `

done

echo "sum is $a"

OUTPUT:

$sh sum.shEnter the number 34Sum is 7$

RESULT: Thus sum of digits of given number is determined using shell script.

17

Page 18: Ex No 1 -4

PROGRAM 4:

AIM: To code a shell script to swap two numbers using only two constraints.

PROGRAM:

#program to swap two numbers using only two constraints

echo " enter two number to swap"input()

{read aread b

}swapk(){

a=` expr $a \+ $b `b=` expr $a \- $b `a=` expr $a \- $b `

}output(){

echo " the swapped numbers are "echo "$a"echo "$b"

}inputswapkoutput

OUTPUT:

$sh swap.shenter two number to swap 56 74The swapped numbers are 74 56$

RESULT: Thus swapping of two numbers is done using shell script.

18

Page 19: Ex No 1 -4

PROGRAM 5:

AIM: To code a shell script to print the Fibonacci series up to n.

PROGRAM:

#program to generate fibonacci series

echo "enter the number"read nf1=0f=0f2=1echo "fibonacci series is "while [ $f -lt $n ]do{

f=`expr $f1 \+ $f2 `f1=$f2f2=$fecho "$f"

}done

OUTPUT:

$sh fibonacci.shenter the number 55fibonacci series is011235813213455$

RESULT: Thus fibonacci series for a given number is displayed using shell script.

19

Page 20: Ex No 1 -4

PROGRAM 6:

AIM: To code a shell script to find the reverse of n numbers.

PROGRAM:

#program to reverse n numbers

echo "enter the number"read nx=0y=0while [ $n -ne 0 ]do{

x=`expr $n \% 10 `y=`expr $y \* 10 \+ $x `n=`expr $n \/ 10 `

}doneecho "$y"

OUTPUT:

$sh reverse.shenter the number 5432112345$

RESULT: Thus the reverse of ‘n’ numbers is found using shell script.

20

Page 21: Ex No 1 -4

PROGRAM 7:

AIM: To code a shell script to find factorial of a given number.

PROGRAM:

#program to find factorial of given number

echo "enter the number"read nfa=1i=1while [ $i -le $n ]do{

fa=`expr $fa \* $i`i=`expr $i \+ 1`

}doneecho "the factorial of number is $fa "

OUTPUT:

$sh factorial.shEnter the number 3The factorial of number is 6$

RESULT: Thus factorial of a given number is determined using shell script.

21

Page 22: Ex No 1 -4

PROGRAM 8:

AIM: To code a shell script to find greatest of three numbers.

PROGRAM:

# program to find greatest of three numbers

echo " greatest of three numbers"echo "enter three numbers"read aread bread cif [ $a -gt $b -a $a -gt $c ]then

echo "$a is greatest"elif [ $b -gt $a -a $b -gt $c ]then

echo "$b is greatest"else

echo "$c is greatest"fi

OUTPUT:

$sh greatest.shgreatest of three numbersenter three numbers 6 5 88 is greatest$

Result: Thus greatest of three numbers is found using shell script.

22

Page 23: Ex No 1 -4

PROGRAM 9:

AIM: To code a shell script to determine whether the given number is prime or not prime.

PROGRAM:

#program to determine whether the given number is prime or not prime.

echo " enter the number"read noi=2ci=0flag=1while [ $i -le $no ]do{

ci=`expr $no \% $i`if [ $ci -eq 0 ] then

flag=0fi i=`expr $i \+ $i`

}done

if [ $flag -eq 1 ] then

echo "\nnumber is prime"else

echo "\nnumber is not prime"fi

OUTPUT:$sh prime or odd.shenter the number 5number is prime$

RESULT: Thus a number is determined whether it is prime or not prime using shell script.

23

Page 24: Ex No 1 -4

PROGRAM 10:

AIM: To code a shell script to find the sum of negative numbers.

PROGRAM:

#program to sum the negative numbers

sum=0echo "enter the total number of elements"for i in 1 2 3 4 5do{

read xi=` expr $i \+ 1 `if [ $x -lt 0 ]then

sum=` expr $sum \+ $x `fi

}doneecho "the sum of negative numbers is $sum"

OUTPUT:

$sh prime.shenter the total number of elements 51 -2 3 -5 -6the sum of negative numbers is -13$

RESULT: Thus the sum of negative numbers is determined using shell script.

24

Page 25: Ex No 1 -4

PROGRAM 11:

AIM: To code a shell script to find the Armstrong number.

PROGRAM:

#program to find armstrong number

echo "enter the number"read nrem=0num=$nsoc=0while [ $num -ne 0 ]do

rem=`expr $num \% 10`cube=`expr $rem \* $rem \* $rem`soc=`expr $soc \+ $cube`num=`expr $num \/ 10`

doneif [ $soc -eq $n ]then

echo " $n is an armstrong number"else

echo " $n is not an armstrong number"fi

OUTPUT:

$sh Armstrong.shenter the number 370370 is an armstrong number$

RESULT: Thus a number is checked whether it is Armstrong or not using shell script.

25

Page 26: Ex No 1 -4

RESULT:Thus the above shell programs are executed and the output is

verified.

26

Page 27: Ex No 1 -4

EX NO: 3 STUDY OF SYSTEM CALLS OF UNIX DATE:

AIM:

To study system calls in operating systems.

THEORY:

System calls provide the interface between a process and the operating system. These calls are generally available as assembly-language instructions, and they are usually listed in the various manuals used by the assembly-language programmers.

System calls can be made directly from a higher-level language program, in which case the calls normally resemble pre-defined function or subroutine calls. They may generate a call to a special run-time routine that makes the system call or the system call may be generated directly in-line.

Several languages-such as c, c++, perl-have been defined to replace assembly language for systems programming.

System calls can be grouped roughly into five major categories: process control, file management, device management, information maintenance, and communications.

Some of the system calls are:

Fork ( ) - to create a child process.

fork creates a child process that differs from the parent process only in its PID and PPID, and in the fact that resource utilizations are set to 0. File locks and pending signals are not inherited.

Under Linux, fork is implemented using copy-on-write pages, so the only penalty incurred by fork is the time and memory required to duplicate the parent's page tables, and to create a unique task structure for the child.

Getpid ( ) – to get parent id.

27

Page 28: Ex No 1 -4

getpid returns the process ID of the current process. (This is often used by routines that generate unique temporary file names.)

Getppid ( ) – to get parent process id.

getppid returns the process ID of the parent of the current process.

Wait ( ) – to synchronize between child and parent process.

The wait function suspends execution of the current process until a child has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function. If a child has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed.

Excelp()- call process within another process

The exec family of functions replaces the current process image with anew process image. The functions described in this manual page arefront-ends for the function execve(2).The initial argument for these functions is the pathname of a file which is to be executed.

Stat ( ) – used to get the status of a file.

These functions return information about the specified file.You do not need any access rights to the file to get this information but you need search rights to all directories named in the path leading to the file.

stat stats the file pointed to by file_name and fills in buf.

28

Page 29: Ex No 1 -4

PROGRAM 1:

Aim:-To code a program to create a child process using fork

Program:

//Program to create a child process using fork ( )

main ( ){

printf (“\nhello\n”);fork ( );printf(“welcome\n”)

}

Output:

$cc fork.c$./a.outhellowelcomewelcome$

Result:-Thus a program to create a child process is written.

29

Page 30: Ex No 1 -4

PROGRAM 2:

Aim:-To code a program to find the parent and child process id.

Program:

//program to get the parent and child process id

Main ( ){

Printf (“process id= %d”, getpid ( ));Printf (“\nparent process id= %d”, getppid ( ));

}

Output:

$cc pid.c$./a.outProcess id= 12615Parent process id= 11522$

Result:- Thus a program to find parent and child process id is written.

30

Page 31: Ex No 1 -4

PROGRAM 3:

Aim:-To code a program to get parent id using fork command.

Program:

//program to get the parent id using fork ( )

Main ( ){

int id;Id=fork ( );If (id>0) Printf (“the parent id=%d”, id);

}

Output:$cc pid_fork.c$./a.outThe parent id=13638$

Result:- A program to get the parent id using fork command is written.

31

Page 32: Ex No 1 -4

PROGRAM 4:

Aim:-A program to call a process within a another process using execlp.

Syntax: execlp (“directory”, filename, NULL);

Program://program to call process within another process using execlp

main(){ printf("%d",getpid()); printf("\nhello"); execlp("home/it027","execlp.c",NULL); printf("\nthankyou");}

Output:-$cc ExPid.c$./a.out1160hellothankyou$

Result:-Thus a program to call a process within a another process is

Written.

32

Page 33: Ex No 1 -4

PROGRAM 5:

Aim:-To code a program for synchronization of parent and child process.

Program://wait- used for synchronization between parent and child process.

main() { pid=fork(); if(pid>=0) { //child process for(i=0;i<=5;i++) { printf("%d",i); printf("child ends"); } } else { wait(0); printf("parentprocess"); } }

Output:$cc sync.c$./a.out01234child ends01234child ends$

Result:-Thus a program to synchronize parent and child process is written.

33

Page 34: Ex No 1 -4

PROGRAM 6:

Aim:- To code a program to check the status of the file.

Program://program to check the status of the file

#include<sys/types.h> #include<sys/stat.h> #include<errno.h> #include<string.h> void main() { char *f1; struct stat buf; strcpy(f1,"system5.c"); if(stat(f1,&buf)==0) printf("\nthe uid %d"buf.st_uid); else printf("error has occured"); }

Output:$cc status.c$./a.outThe uid 1627$

Result:-Thus a program to check the status of the file is written.

34

Page 35: Ex No 1 -4

RESULT:- Thus the various system calls have been studied.

35

Page 36: Ex No 1 -4

EX NO: 4

DATE: I/O SYSTEM CALLS OF UNIX

AIM:To create, open, rename and delete a file using system calls.

THEORY:

System calls form the interface between the UNIX kernel and the user programs that run on top of it. Those who interact only with commands, like the shell, text editors, and other application programs, may have little need to know much about system calls, but a thorough knowledge of them is essential for UNIX programmers. System calls are the only way to access kernel facilities such as the file system, the multitasking mechanisms, and the inter process communication primitives.

System calls define what UNIX is. Everything else -- subroutines and commands -- is built on this foundation. While the novelty of many of these higher-level programs has been responsible for much of UNIX's renown, they could as well have been programmed on any modern operating system. When one describes UNIX as elegant, simple, efficient, reliable, and portable, one is referring not to the commands (some of which are none of these things), but to the kernel.

36

Page 37: Ex No 1 -4

Program 1:

Aim:

To create a file using creat command.

Program :

(a) To create a file:

#include<stdio.h>#include<sys/stat.h>#include<sys/types.h>#include<unistd.h>

int main(){

char fname[30];int fd;printf(“\n\nEnter filename with path:”);scanf(“%s”,&fname);if(fd=creat(fname)<0) //If error in creating file{

perror(“Creat”);exit(0);

}else

printf(“\n\nFile is created successfully”);}

Output:

$ cc createfile.c

$ ./a.out

enter the file name with the path it032/file/program.c

file is successfully created

$

Result:

Thus the file is created successfully.

37

Page 38: Ex No 1 -4

Program 2:Aim:

To open a file using open command.

Program:

(b) To open a file:

#include<stdio.h>#include<sys/file.h>#include<limits.h>main(){

char *fn=”/home/it016/abcd.c”;int fd;printf(“\nOpening file %s“,fn);

//O_RDWR-Open for reading and writing//O_CREAT-Create the file if it doesn’t exist

if((fd=open(fn,O_RDWR/O_CREAT))<0) //If file doesn’t exist{

perror(“Open”);exit(1);

}else

printf(“\nFile is opened successfully”);if(close(fd)<0){

perror(“Close”);exit(1);

}}

Output:$ cc openf.c$ ./a.out

opening the file /home/it032/file/ipcpipes.c

file is opened successfully$

Result:

Thus the file is opened successfully.

38

Page 39: Ex No 1 -4

Program 3:

Aim:

To read a file using read command.

Program:

(c) To read a file:

#include<stdio.h>#include<sys/file.h>#include<limits.h>main(){

char *fn=”/home/it032/abcd.c”;int fd;int actualbytes,bytesstored;char buffer[1000];printf(“\nOpening file %s”,fn);if((fd=open(fn,O_RDWR,O_CREAT))<0){

perror(“Open”);exit(0);

}printf(“Reading the file %s”,fn);bytesstored=1024;

//read(int fildes,void *buf,size_t nbyte)//The read function attempts to read nbyte bytes from the file

//associated with the open file descriptor, fildes, into the //buffer pointed to be buf.

if((actualbytes=read(fd,buffer,bytesstored))<0){

perror(“Read”);exit(0);

}else{

printf(“\nFile is opened”);printf(“\nContents of file is:%s”,buffer);

}

if(close(fd)<0){

perror(“Close”);

39

Page 40: Ex No 1 -4

exit(0);}exit(0);

}

Output:$ cc readfile.c$ ./a.out

opening file /home/it032/fork.c

reading the file

file is opened

contents of file is #include <stdio.h>main(){printf(" \n hello world ");fork();printf(" \n thank u ");}

$

Result:

Thus the file is opened and the contents are read successfully.

40

Page 41: Ex No 1 -4

Program 4:

Aim:

To rename a file using rename command.

Program:

(d) To rename a file:

#include<stdio.h>main(){

char oldname[30],newname[30];printf(“\nEnter name of file to be replaced:”);scanf(“%s”,&oldname);printf(“\nEnter new name of file:”);scanf(“%s”,&newname);

//rename command compares the name of both the files and if the //output produced by it is zero, it changes to the new name of the //file.

if(rename(oldname,newname)==0)printf(“\n Successfully %s is renamed to %s”,oldname,

newname);}

Output: $ cc rename.c

$ ./a.outEnter name of file to be replaced 1234.cEnter new name of file 123.c

sucessfully 1234.c renamed as 123.c$

Result:

Thus the file is renamed successfully.

41

Page 42: Ex No 1 -4

Program 5:

Aim:

To remove a file using unlink command.

Program:

(e) To remove a file:

#include<stdio.h>main(){

char fname[30];printf(“\nRemoving a file”);printf(“\nEnter filename with path:”);scanf(“%s”,&fname);

//unlink deletes a name from the file system. If that name was the //last link to a file and no processes have the file open the file is //deleted and the space it was using is made available for reuse.

if(unlink(fname)<0){

perror(“Unlink”);exit(0);

}

elseprintf(“\nThe file is removed”);

}

Output:

$ cc remove.c$ ./a.out

Removing a fileEnter filename with path: /home/it032/eg.cThe file is removed

Result:

Thus the file is removed successfully.

42

Page 43: Ex No 1 -4

Program 6:

Aim:

To write the contents into a file using write command.

Program:

(f) To write a file:

#include<stdio.h>#include<sys/file.h>#include<fcntl.h>#include<sys/types.h>#include<limits.h>main(){

char fn[30];int fd;int actualbytes,bytesstored;char buffer[100];printf(“\nEnter filename with path:”);scanf(“%s”,&fn);printf(“\nEnter contents of file:”);scanf(“%s”,&buffer);printf(“\nOpening file %s”,fn);

//fopen(name,options);//const char *name; is a string containing the name of the file //to be opened.//const char *options; is a string specifying whether the file //should be opened for reading or writing.

if((fd=fopen(fn,O_RDWR/O_CREAT/O_RDONLY,0644))<0){

perror(“Open”);exit(0);

}

printf(“\nWriting contents to file”);bytesstored=100;

//write(int fd, const void *buf, size_t count);

43

Page 44: Ex No 1 -4

//write writes up to count bytes to the file referenced by the //file descriptor fd from the buffer starting at buf. POSIX requires //that a read() which can be proved to occur after a write() has //returned returns the new data.

if((actualbytes=write(fd,buffer,bytesstored))<0){

perror(“Write”);exit(0);

}

else{

printf(“\nFile is opened”);printf(“\nThe contents are written”);

}

if(close(fd)<0){

perror(“Close”);exit(0);

}

exit(0);}

Output:$ cc write.c$ ./a.out

ENTER FILENAME WITH PATH 123.c

ENTER THE CONTENTS OF FILE I/O system calls in unix

OPENING FILE 123.c WRITING CONTENTS TO FILE THE CONTENTS ARE WRITTEN$

Result:

Thus the contents are written into the file successfully.

44

Page 45: Ex No 1 -4

RESULT:

Hence the various system calls create, open, write, read, open, rename and removing of files is done.

45


Recommended