Ex No 1 -4

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Ex No 1 -4 as PDF for free.

More details

  • Words: 5,405
  • Pages: 45
Ex.No:1 DATE:

STUDY OF UNIX COMMANDS

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:

1

• • •

An open-source UNIX-like operating system. Initially created by Linus Torvalds for PC architecture. Developer community world-wide contribute to its enhancement and growth.

UNIX System Architecture: USER shell Wc

sort sh sh

Kernel hardware

ed

Vi a.out shell 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 Processing 3. I/O redirection. 4. Pipes 5. Shell Scripts 2

6. Shell variables 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 system 2. Processing environment. 3. Building block primitives.

1. File System: The main features of the UNIX file system are: 1. 2. 3. 4. 5. 6.

Hierarchical structure. Consistent treatment of file data. Create and delete files. Dynamic growth of files. Protection of file data. 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 Owner File Owner’s group Others Read(r), Write (w), Execute(X) permissions can be set for each file. 2.Processing Environment:

3

• • • •

A process is a program in execution. 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.

4

The priority levels in descending order are: 1. Machine error 2. Clock 3. Disk 4. Network Devices 5. Terminals 6. Software int 7. 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. $date Thu Oct 15 09:34:50 PST 2006 2. Who: Gives the details of the users who have logged in to the system. $who abc tty0 oct 15 11:17 xyz 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 i user1 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

/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

$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 – read w – write x – execute mode = mode in absolute format is based on octal numbers representing the three kinds of access permissions. 4 read 2 write 1 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 $wc –c display the number of characters

7

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 file2 option –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] file option –d dictionary order option –n arithmetic order option –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: In vi, you need to shift from command mode to edit mode and back again.

8

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 a I A x X o O dd cc r R s

Insert text before a character add text after a character insert text at the beginning of a line insert text at the end of a line delete the current character delete the previous character open a new blank line after the current line Open a new blank line before the current line delete the current line change the current line replace one character replace several characters 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 :w :q :q!

Save the edited file and exit from the editor Save the edited file and stay in the editor Quit the editor Quit the editor under any conditions

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

EXNO:2 DATE:

STUDY OF SHELL PROGRAMS

9

AIM: a) b) c) d) e) f)

TO study and perform some shell programming utilities like: To develop menu driven command r. Outline. Finding the number is even or odd ,sum of digits, prime or not factorial of a number and Armstrong number. Finding the duration of a user’s login time. Clean up routine. 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.

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.

10

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

$$? $$ $! $0 $* $@

the number of positional parameters while invoking the 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. The name of command being executed. The list of positional parameters. Same as $*. Except when enclosed in double quotes.

$@

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

11

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 $xvar Hai . COMMANDS IN SHELL: 1. READ Used to get input(data from user) from keyboard and store (data) to variable. Syntax: Read variable1,variable2,……variable N. 2. ECHO Echo command is used to display text or value of variable. Syntax: Echo[options] [string, variables..] Displays text or variables value on screen. 3. TEST Function 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. -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. 12

LOOPING IN SHELL: a) THE FOR LOOP: The general form of for loop in bourne shell is : For variable-name in value1,value2……. Do 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 Done c)The until loop: Until control command Do Done d)The if statement: If control command Then Fi e)If…..then…..else statement: If control command Then Else Fi 13

f)If then……elif then ……else statement: If control comand1 Then Elif control command2 Then Else Fi

PROGRAM 1: AIM: To code a shell script to display message. PROGRAM:

14

#program to display message. #This is my first shell program clear echo "welcome"

OUTPUT: $sh display.sh welcome $

RESULT: Thus a message is displayed using shell script.

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

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.sh enter the number 3 3 is odd number $sh evenorodd.sh enter the number 6 6 is even number $

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

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.

16

echo "enter the number" read x c=0 a=0 while [ $x -ne 0 ] do c=` expr $x \% 10 ` a=` expr $a \+ $c ` x=` expr $x \/ 10 ` done echo "sum is $a" OUTPUT: $sh sum.sh Enter the number 34 Sum is 7 $

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

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

17

echo " enter two number to swap" input() { read a read b } swapk() { a=` expr $a \+ $b ` b=` expr $a \- $b ` a=` expr $a \- $b ` } output() { echo " the swapped numbers are " echo "$a" echo "$b" } input swapk output OUTPUT: $sh swap.sh enter two number to swap 56 74 The swapped numbers are 74 56 $ RESULT: Thus swapping of two numbers is done using shell script.

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" 18

read n f1=0 f=0 f2=1 echo "fibonacci series is " while [ $f -lt $n ] do { f=`expr $f1 \+ $f2 ` f1=$f2 f2=$f echo "$f" } done OUTPUT: $sh fibonacci.sh enter the number 55 fibonacci series is 0 1 1 2 3 5 8 13 21 34 55 $ RESULT: Thus fibonacci series for a given number is displayed using shell script. 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" 19

read n x=0 y=0 while [ $n -ne 0 ] do { x=`expr $n \% 10 ` y=`expr $y \* 10 \+ $x ` n=`expr $n \/ 10 ` } done echo "$y" OUTPUT: $sh reverse.sh enter the number 54321 12345 $

RESULT: Thus the reverse of ‘n’ numbers is found using shell script. 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 n fa=1 i=1 20

while [ $i -le $n ] do { fa=`expr $fa \* $i` i=`expr $i \+ 1` } done echo "the factorial of number is $fa " OUTPUT: $sh factorial.sh Enter the number 3 The factorial of number is 6 $

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

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 a read b 21

read c if [ $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.sh greatest of three numbers enter three numbers 6 5 8 8 is greatest $

Result: Thus greatest of three numbers is found using shell script. 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 no i=2 22

ci=0 flag=1 while [ $i -le $no ] do { ci=`expr $no \% $i` if [ $ci -eq 0 ] then flag=0 fi 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.sh enter the number 5 number is prime $ RESULT: Thus a number is determined whether it is prime or not prime using shell script. PROGRAM 10: AIM: To code a shell script to find the sum of negative numbers. PROGRAM: #program to sum the negative numbers sum=0 echo "enter the total number of elements" for i in 1 2 3 4 5 do { read x i=` expr $i \+ 1 ` 23

if [ $x -lt 0 ] then sum=` expr $sum \+ $x ` fi } done echo "the sum of negative numbers is $sum" OUTPUT: $sh prime.sh enter the total number of elements 5 1 -2 3 -5 -6 the sum of negative numbers is -13 $

RESULT: Thus the sum of negative numbers is determined using shell script. PROGRAM 11: AIM: To code a shell script to find the Armstrong number. PROGRAM: #program to find armstrong number echo "enter the number" read n rem=0 num=$n soc=0 while [ $num -ne 0 ] do rem=`expr $num \% 10` 24

cube=`expr $rem \* $rem \* $rem` soc=`expr $soc \+ $cube` num=`expr $num \/ 10` done if [ $soc -eq $n ] then echo " $n is an armstrong number" else echo " $n is not an armstrong number" fi OUTPUT: $sh Armstrong.sh enter the number 370 370 is an armstrong number $

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

25

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

EX NO: 3 DATE:

STUDY OF SYSTEM CALLS OF UNIX

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

26

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

27

The exec family of functions replaces the current process image with a new process image. The functions described in this manual page are front-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.

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”) } 28

Output: $cc fork.c $./a.out hello welcome welcome $

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

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

29

Output: $cc pid.c $./a.out Process id= 12615 Parent process id= 11522 $

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

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

30

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

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

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

printf("\nthankyou"); } Output:$cc ExPid.c $./a.out 1160 hello thankyou $

Result:Thus a program to call a process within a another process is Written.

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

} } else { wait(0); printf("parentprocess"); } } Output: $cc sync.c $./a.out 01234child ends01234child ends $

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

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

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.out The uid 1627 $

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

34

RESULT:Thus the various system calls have been studied.

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 35

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.

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

36

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. Program 2: Aim: To open a file using open command. Program: (b) To open a file: #include<stdio.h> #include<sys/file.h> #include 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) { perror(“Open”); exit(1); } else

//If file doesn’t exist

37

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. Program 3: Aim: To read a file using read command. Program: (c) To read a file: #include<stdio.h> #include<sys/file.h> #include 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;

38

//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”); 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 "); }

39

$

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

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

40

Output: $ cc rename.c $ ./a.out Enter name of file to be replaced 1234.c Enter new name of file 123.c sucessfully 1234.c renamed as 123.c $

Result: Thus the file is renamed successfully. 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); } else 41

printf(“\nThe file is removed”); } Output: $ cc remove.c $ ./a.out Removing a file Enter filename with path: /home/it032/eg.c The file is removed

Result: Thus the file is removed successfully. 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 #include<sys/types.h> #include 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 42

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

43

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

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

45

Related Documents

Ex No 1 -4
November 2019 7
Ex No 4
November 2019 6
Presentation 1 - Ex 4
November 2019 20
Ex-4
April 2020 13
Ex 4
April 2020 14
Ex 4
November 2019 17