Sunteți pe pagina 1din 271

Unix Commands, Utilities System Programming And Overview of Internals

By: Khaleel Ahmed


09-Sep-2000 Version: 2.1 1

Copyright Notice
Copyright Information Technology Consultants reserves all rights to this document. No part of this literature may be stored in a retrieval system, transmitted, or reproduced in any way, including but not limited to photocopy, photograph, magnetic or other record, without the prior agreement and written permission of Information Technology Consultants
09-Sep-2000 Version: 2.1 2

Schedule Day 1
Overview of Unix Learning the basic commands Customizing the shell environment Job Control Understanding file permissions

09-Sep-2000

Version: 2.1

Schedule Day 2
Shell programming (Korn shell) System Programming
File Systems File Handling System Calls Process Management Process Management System Calls

Unix Architecture
Process Management Data structures and internals File System Data structures and internals
09-Sep-2000 Version: 2.1 4

Schedule Day 3
System Programming
Overview of IPC facilities Using pipes Using named pipes Using shared memory Using message queues

Network Programming Overview of TCP/IP


IP, ARP, ICMP UDP TCP

Using socket system calls


09-Sep-2000 Version: 2.1 5

Unix Overview
Developed at AT&T Bell Lab in 1969 by Ken Thompson on an idle PDP-7. Later moved to a PDP-11. Ken Thompson also developed a new language called B. Denis Ritchie developed C language from B. In 1973, Unix was re-written in C language. This led to its popularity, the number of installations at Bell Lab grew to about 25.
09-Sep-2000 Version: 2.1 6

Unix Overview
As AT&T was not allowed to sell software at that time, it was provided free-of-cost to universities. By 1977, Unix installations grew to about 500, of which 125 were in universities. Licenses of Unix were provided to commercial and educational institutions. Between 1977 and 1982, Bell Labs combined several Unix variants into a single system known as Unix System III.
09-Sep-2000 Version: 2.1 7

Unix Overview
In 1983, Bell Lab announced their support for a new version, known as System V. By this time, University of California at Berkeley had also developed a new variant of Unix, known as 4.3 BSD for VAX machines. The 4.3 BSD provided new features such as reliable signals and TCP/IP.

09-Sep-2000

Version: 2.1

Unix Overview
Neither AT&T nor BSD is now active in Unix development so most new developments are now defined by a specific vendor or a body such as IEEE (POSIX standard), FreeBSD organization or the Linux community. Today, Linux is adding to Unixs popularity. However, Linux is a Unix-clone and not Unix as the kernel was written from scratch and other tools have been largely taken from the FSF (Free Software Foundation).
09-Sep-2000 Version: 2.1 9

Unix Overview
Chronological evolution of Unix:
Year 1969 1973 1976 1978 1982 1983 1984 1987 1988 1992 From Bell Lab /AT&T First Edition Fifth Edition Sixth Edition Seventh Edition System III System V System V, Release 2 System V, Release 3 System V, Release 4 From BSD

3 BSD 4.1/4.1a BSD 4.2 BSD 4.3 BSD 4.3 BSD Tahoe 4.4 BSD

09-Sep-2000

Version: 2.1

10

Unix Overview
Various Unix Flavors
Product AIX HP Ux Solaris Tru64Unix IRIX SCO Unix From IBM HP Sun Compaq SGI SCO Version

09-Sep-2000

Version: 2.1

11

Unix Overview
Multi-user and multi-tasking environment Provides virtual memory support Devices are treated as files Provides more than one type of shells (command interpreters)

09-Sep-2000

Version: 2.1

12

Unix Overview
Provides more than one mechanism for interprocess communication (IPC) . Excellent networking support through TCP/IP. The standard Unix File system is fast, but not very robust many vendors have introduced their own robust versions.

09-Sep-2000

Version: 2.1

13

Unix Overview
Most system operations depend upon the configuration files such as /etc/passwd, /etc/group, /etc/hosts, /etc/services etc. Default system security can be enhanced through installation of additional security packs. Supports the X-Window system as a GUI. Supports POSIX standards to a large extent.

09-Sep-2000

Version: 2.1

14

Unix Architecture
Utility, command or shell script shell
User Mode Kernel Mode

system calls
File System
Kernel

I/O System

Memory Manager

Scheduler

Buffer Cache

Interrupt and Exception Handlers

09-Sep-2000

Version: 2.1

15

Function of a shell
Displays a prompt where the user can enter a new command. Validates the command entered by the user. Creates a new process using fork() or similar system call. Executes the command using one of exec() family of system calls.
09-Sep-2000 Version: 2.1 16

Function of a shell
Waits for a.out to complete using the wait() or similar system call, provided the command is not being run as a background job.
Note: Not all shells provide background job facility.

Displays the prompt again, once the command is complete, or immediately displays the prompt if it is a background job.

09-Sep-2000

Version: 2.1

17

Function of a shell
A shell also provides a programming environment through a combination of :
standard Unix utilities and commands built-in shell commands

The programs written to work in environment of a shell are called shell scripts. A shell script is a text file containing above commands.

09-Sep-2000

Version: 2.1

18

The process concept


A process is a program in execution. It is created by Unix to run a program. Each process in Unix is allocated a time slice. When a process consumes the time slice, Unix stops the process and resumes another process. In order to ensure that a process can be stopped and re-started as and when required, Unix stores a number of attributes for every process.
09-Sep-2000 Version: 2.1 19

Next Topic

Basic Unix Commands

09-Sep-2000

Version: 2.1

20

Your Unix User Account


Your Unix user account will have a login name and most probably a password. In addition, a number of other attributes are associated with a user account in Unix. The four most important attributes are:
Home Directory Pathname Login Shell Pathname User ID Group ID
Version: 2.1 21

09-Sep-2000

Your Login Process


Once you log in, Unix creates a process for you, and runs the login shell as a program in that process. For the login shell process, Unix makes your home directory as the current directory. Therefore, after login, by default, you will be working with your home directory.

09-Sep-2000

Version: 2.1

22

Your Login Process


When you log into Unix, your login shell also executes a startup script for you from your home directory. The name of this script depends upon the login shell. For Bourne shell, this file is .profile file. For C-shell, this file is .cshrc file. To customize your login environment, you can modify these startup scripts.
09-Sep-2000 Version: 2.1 23

Using Unix Commands


Most Unix commands are individual programs that perform various tasks. Unix has a large set of commands that are described related reference (man) pages. When you enter a command, the shell interprets the command, and then gives an appropriate response -- that is, the system either runs the program or displays an error message. If the command is valid, the shell directs the operating system to do what is requested.
09-Sep-2000 Version: 2.1 24

Using Unix Commands


The shell acts as a command interpreter in the following way:
The shell displays a shell prompt and waits for you to enter a command. You enter a command, the shell analyzes it, and locates the requested program. The shell asks the system to run the program, or it returns an error message. When the program completes execution, control returns to the shell, which again displays the prompt.

09-Sep-2000

Version: 2.1

25

Setting Your Password


To set your password, use the passwd command. If your account does not have a password, use the passwd command to set one. If your system is part of a networked system, you must use the yppasswd command to establish or change your password. Your system administrator can advise you on the specific procedures for your system.
09-Sep-2000 Version: 2.1 26

Getting Help
Many basic commands are covered in this course. If you want to learn more about these and other commands, see the man pages. When hard copy documents are not available, you can access online documentation by using the following commands:
The man command displays online reference pages. The apropos command displays a one line summary of each command pertaining to a specified subject.
09-Sep-2000 Version: 2.1 27

Getting Help
The apropos command and man -k command are useful tools if you forget a command name. These commands require access to the whatis database. This database must be installed. Both these commands let you enter a command description in the form of keywords. The commands then list all the reference pages that contain any of the keywords.

09-Sep-2000

Version: 2.1

28

Getting Help
Assume that you cannot remember the name of the command that displays who is logged in to the system. To display the names and descriptions of all man pages that are related to users who are logged in, enter one of the following: $ apropos "logged in" or $ man -k 'logged in'
09-Sep-2000 Version: 2.1 29

Manipulating files and directories


In Unix, each file is a series of bytes without any structure (format). The directory is the only file that has a structure imposed on it. Each file has one or more names. Each file is also stored in a directory. The directories are stored in the file system. A file system is the useful arrangement of files into directories.
09-Sep-2000 Version: 2.1 30

Listing files and directories


In Unix, each file has a number of attributes associated with it. Some of these are:
File type File permissions File owner user ID and group ID File size Date/time of creation, last update and last access Number of hard links

09-Sep-2000

Version: 2.1

31

File names
A file name can contain any character except the following because these have special meaning to the shell:
Slash (/) Backslash (\) Ampersand (&) Left- and right-angle brackets (< and >) Question mark (?) Dollar sign ($) Left bracket ([) Asterisk (*) Tilde (~) Vertical bar or pipe symbol (|)

09-Sep-2000

Version: 2.1

32

File names
You may use a period or dot (.) in the middle of a file name. If you use a dot at the beginning of the file name it will be hidden when doing a simple listing of files thru the ls command. The maximum length of a file name depends upon the file system used. Most new file system allow a maximum length of 255 characters (the default). Older file systems allow a maximum file name length of only 14 characters.
09-Sep-2000 Version: 2.1 33

Name of current working directory


The directory in which you are working at any given time is your current, or working directory. If you are uncertain about the directory in which you are working, enter the pwd (print working directory) command. You can use the cd command to move to your home directory from any location.
09-Sep-2000 Version: 2.1 34

Understanding pathnames
A pathname specifies the location of a directory or a file within the file system. A pathname consists of a series of directory names separated by slashes (/) that ends with a directory name or a file name. A pathname that starts with a slash (/) is called a full pathname or an absolute pathname.
09-Sep-2000 Version: 2.1 35

Understanding pathnames
You can also think of a full pathname as the complete name of a file or a directory. Regardless of where you are working in the file system, you can always find a file or a directory by specifying its full pathname. The file system also lets you use relative pathnames. Relative pathnames do not begin with the / that represents the root directory because they are relative to the current directory.
09-Sep-2000 Version: 2.1 36

Understanding pathnames
You can specify a relative pathname in one of several ways:
As the name of a file in the current directory. As a pathname that begins with the name of a directory one level below your current directory. As a pathname that begins with .. (dot dot, the relative pathname for the parent directory). As a pathname that begins with . (dot, which refers to the current directory). This relative pathname notation is useful when you want to run your own version of an operating system command in the current directory (for example ./ls).

09-Sep-2000

Version: 2.1

37

Understanding directories
In Unix, a directory is a file that has a number of entries. Each entry contains:
A filename The I-node number of the file

Every directory contains at least two entries:


Filename of .. (dot dot) Filename of. (dot)

09-Sep-2000

Version: 2.1

38

Understanding directories
In the C shell and the Korn or POSIX shell, you may also use a tilde (~) at the beginning of relative pathnames. The tilde character used alone specifies your home directory. The tilde character followed by a user name specifies the home directory of that user. For example, $ cd ~/mydir $ cd ~micky/mouse
09-Sep-2000 Version: 2.1 39

Listing files and directories


You can use the ls command to list files. The syntax of this command is: ls [options] [directory_names] Some of the options are:
-a, for all file names -d, to list only directory names -l, for a long (detailed) listing -R, for a recursive listing (traverse sub-directories) -t, for listing recently modified files
Version: 2.1 40

Examples: $ ls $ ls l $ ls -Rl

09-Sep-2000

Listing files and directories


Examples: $ $ ls -l total 4 [1] -rw-r--r--rw-r--r--rw-r--r--rw-r--r-drwxr-xr-x 1 1 1 1 2

[2] larry larry larry larry larry

[3] system system system system system

[4]

[5]

[6]

[7]

101 Jun 5 10:03 file1 75 Jun 5 10:03 file2 75 Jun 5 10:03 file2 65 Jun 5 10:06 file3 32 Jun 5 10:07 project

1. 2. 3. 4. 5. 6. 7.

Number of 512-byte blocks used by files in this directory. Number hard of links to each file. User name of the file's owner. Group to which the file belongs. Number of bytes in the file. Date and time the file was created or last modified. Name of the file or directory.
Version: 2.1 41

09-Sep-2000

Listing files and directories


Examples: $ ls -l total 2 -rw-r--r-- 1 larry system 101 Jun 5 10:03 file1 drwxr-xr-x 2 larry system 32 Jun 5 10:07 project $

The drwxr-xr-x indicates file type and permissions for each file. More about these permissions later

09-Sep-2000

Version: 2.1

42

Listing files and directories


Following are some of the file types:
- (hyphen) b c d l p s for ordinary files for block-special files for character-special files for directories for symbolic links for pipe-special files (first in, first out) for local sockets

09-Sep-2000

Version: 2.1

43

Finding the type of a file


Use the file command to see what kind of data a file contains. The file command displays whether the file is one of the following:
A text file A directory A FIFO (pipe) special file A block special file A character special file Source code for the C or FORTRAN languages An executable (binary) file An archive file in ar format

(continued)
09-Sep-2000 Version: 2.1 44

Finding the type of a file


An archive file in extended cpio or extended tar format An archive file in zip format A compressed data file in gzip format A file of commands text (shell script) An audio file in .voc, .iff, or .wav format An image file in TIFF, GIF, MPEG, or JPEG format

This command is especially useful when you suspect that a file contains a compiled program, audio data, or image data. Displaying the contents of these types of files can produce strange results on your screen.
09-Sep-2000 Version: 2.1 45

Creating/Deleting Directories
You can use the mkdir command to create directory or sub-directories.
Examples: $ mkdir c_progs $ mkdir c_progs/shared

You can use rmdir command to delete a directory. The directory must be empty. You can also use the rm command with r (recursive) option. Examples:

$ rmdir c_progs $ rmdir c_progs/shared

09-Sep-2000

Version: 2.1

46

Viewing files
You can use the cat command to view a file on screen. Examples:
$ $ cat test.c $ cat *.c

You can also use the cat command to create a file.


Examples: $ cat >> file1 This is line 1. This is line 2. ^D $

09-Sep-2000

Version: 2.1

47

Viewing files
Following commands can also be used to display a file :
pg more page

The pg command lets you view one or more files. When you display files that contain more lines than will fit on the screen, the pg command pauses as it displays each screen.
09-Sep-2000 Version: 2.1 48

Printing files
If your system has more than one printer, use following format to specify where you want the file to print: lpr -P printername filename The -P flag specifies a printer. The printername is the name of a printer. Printers often have names that describe the location of the printer, the custodian or nearest monitor, or some other descriptive name. Contact system administrator for info. on printer names.
09-Sep-2000 Version: 2.1 49

Viewing Print Queues


To see the position of the request in the print queue, use the lpq command. If there are no requests in the print queue, the system responds with the following message: no entries If there are entries in the queue, the system lists them and indicates what is currently being printed.
09-Sep-2000 Version: 2.1 50

Viewing Print Queues


Following is a typical lpq listing :
Rank active bytes 1st 2nd 3rd Owner Job marilyn sue juan larry 135 360 490 Files 489 Total Size report 8470

letter 5444 bytes (standard input) 969 bytes travel 1492 bytes

The lpq displays following for each print job:


Its position in the queue Its owner Its job number Name of the file Size of the file in bytes
Version: 2.1 51

09-Sep-2000

Copying files and directories


The cp (copy) command copies a file from one name to another name in your current directory or copies the file from one directory to another directory.
Examples: $ $ cp file2 file2x $ $ mkdir reports $ cp file2 reports

09-Sep-2000

Version: 2.1

52

Renaming/Deleting Files
You can use the mv command to rename or move a file.
Examples: $ $ mv test.c newtest.c $ mv test.c c_progs $ mv test.c c_progs/newtest.c

You can use the rm command to delete a file.


Examples: $ $ rm test.c $ rm c_progs/*.c $ rm c_progs/newtest.c

09-Sep-2000

Version: 2.1

53

I/O Redirection
For every program, Unix automatically opens three files. These files are:
Standard input (file descriptor 0) Standard output (file descriptor 1) Standard error (file descriptor 2)

Normally, the standard output and standard error file refer to the monitor whereas the standard input file refers to the keyboard.

09-Sep-2000

Version: 2.1

54

I/O Redirection
By using the I/O redirection facility, you can redirect output and error messages to a file. You can also take the input from a file. To redirect standard output, you can use the > symbol.
Examples: $ $ ls -Rl / > allfiles $ cat test.c > copytest.c

09-Sep-2000

Version: 2.1

55

I/O Redirection
To append standard output to an existing file, use >> symbol.
Examples: $ $ ls l *.c >> file_list

Note: The file will be created if it does not exist.

To redirect standard error, use 2> symbol.


Examples: $ $ cat test.c junk.c 2> errors Note: Assumes that file junk.c does not exist.

09-Sep-2000

Version: 2.1

56

I/O Redirection
To redirect standard input from an existing file, you can use the < symbol. In general, any command that expects input from the keyboard can take the redirected input from a file.
Examples: $ $ cat < file_list $ mail s this is a file user1 < my_message

09-Sep-2000

Version: 2.1

57

Piping
The piping facility allows you to send the standard output from one program as input to another program.
Examples: $ $ ls l | wc l $ who | wc l $ ls l test.c junk.c | wc l

(output of ls is sent to wc) (output of who is sent to wc) (only output of ls is sent to wc)

Note: The last example assumes that file junk.c does not exist.

09-Sep-2000

Version: 2.1

58

Matching filenames
If the file names have a common pattern, the shell can match that pattern, generate a list of those names, and automatically pass them to the command as arguments. The asterisk (*), sometimes referred to as a wildcard , matches any string of characters.
Examples: $ ls file *

09-Sep-2000

Version: 2.1

59

Matching filenames
If the file names have a common pattern, the shell can match that pattern, generate a list of those names, and automatically pass them to the command as arguments. The asterisk (*), sometimes referred to as a wildcard , matches any string of characters. For example, file* will match any filename starting with word file.

09-Sep-2000

Version: 2.1

60

Matching filenames
There is one exception to the general rules for pattern matching. When the first character of a file name is a period, you must match the period explicitly. For example, ls * displays the names of all files in the current directory except those that begin with a period. The command ls -a displays all file names, including those that begin with a period.

09-Sep-2000

Version: 2.1

61

Matching filenames
This restriction prevents the shell from automatically matching the relative directory names. These are . (for the current directory) and .. (for the parent directory). In addition to the asterisk (*), shells provide other ways to match character patterns. These are summarized in the next slide.

09-Sep-2000

Version: 2.1

62

Matching filenames
The filename pattern-matching characters are:
* ? [] [.-.] [!] matches any string, including NULL matches any single character matches any of the set characters matches any character within the specified range matches any character except those in the set

09-Sep-2000

Version: 2.1

63

Hard Links and Soft Links


There are two kinds of links available for your use:
hard links soft, or symbolic, links

When you create a hard link, you are providing another name for the same file. Hard links let you link only files in the same file system. All the link names are on equal footing. It is incorrect to think of one file name as the real name, and another as only a link.
09-Sep-2000 Version: 2.1 64

Hard Links and Soft Links


Soft links or symbolic links let you link both files and directories. In addition, you may link both files and directories across different file systems. A symbolic link is actually a distinct file that contains a pointer to another file or directory. This pointer is the pathname to the destination file or directory. Only the original file name is the real name of the file or directory. Unlike a hard link, a soft link is actually only a link.
09-Sep-2000 Version: 2.1 65

Creating Links
To link a hard link, use the following command format: ln <existing_pathname> <new_pathname> If you want to link files and directories across file systems, you can create symbolic links. To create a symbolic link, add an -s flag to the above ln command and specify full pathnames of both files.
09-Sep-2000 Version: 2.1 66

Understanding Links
Each file has a unique identification, called an Inode number. The I-node number refers to files data stored at a particular location - rather than to the file name. A directory entry is a link between an I-node number and a file name. This link enables you to link multiple file names to the same I-node number. To display I-node number of files, use ls with the -i flag.
09-Sep-2000 Version: 2.1 67

Understanding Links
Hard links to a file carry the same I-node number. Since an I-node number represents a file within a particular file system, hard links cannot exist between file systems. However, the soft link is a new file with its own, new I-node number. Since the soft link refers to the original file by name, rather than by I-node number, they work across file systems.
09-Sep-2000 Version: 2.1 68

Deleting Links
The rm (remove file) command does not always remove a file. Assume that a file has several hard links (and therefore more than one file name). In this case, the rm command removes the link between the file I-node number and that file name, but leaves the physical file intact. The rm command physically removes a file only after it has removed the last link between that file and its names.
09-Sep-2000 Version: 2.1 69

Viewing File System Info


The df command to displays the disk partition that holds a particular directory. Examples show that directories /u1/info and /etc are in different file systems, but that /etc and /tmp are in the same file system:
$ df /u1/info Filesystem 512-blks used avail capacity Mounted on /dev/rz2c 196990 163124 14166 92% /u1 $ df /etc Filesystem 512-blks used avail capacity Mounted on /dev/rz3a 30686 19252 8364 70% / $ df /tmp Filesystem 512-blks used avail capacity Mounted on 09-Sep-2000 Version: 2.1 70 /dev/rz3a 30686 19252 8364 70% / $

Understanding Unix Security


Every valid user is known to the system through a user account. When a user account is created, information about the user is added to the following two files:
/etc/passwd - This file contains individual user information for all users of the system. /etc/group - This file contains group information for all groups on the system.

These files define who can use the system and each user's access rights.
09-Sep-2000 Version: 2.1 71

The /etc/passwd file


The /etc/passwd file contains records that define login accounts and attributes for all system users. This file can be altered only by a user with super-user privileges. Each record in the /etc/passwd file defines a login account for an individual user. The fields are separated by colons. The format of an /etc/passwd file entry is as follows:
username:password:UID:GID:gecos:login_directory:login_shell

09-Sep-2000

Version: 2.1

72

Fields in /etc/passwd entry


username - Your login name. password - Your password stored in encrypted form. UID - A unique number identifying you to the system. GID - A number identifying your default group. You can belong to one or more groups. gecos - This field usually contains general information about you, stored in some installation specific format. login_directory - Your current directory after logging in to the system. login_shell - The program run by the login program after you successfully log in to the system.

09-Sep-2000

Version: 2.1

73

The /etc/group file


The /etc/group file defines login accounts for all groups using the system. This file can be altered only by a user with super-user privileges. Each entry in this file defines the login account of one group. Groups provide a convenient way to share files among users who are working on the same project. The format of each entry is :
09-Sep-2000

groupname:password:GID:user1[,user2,...,user Version: 2.1 74 N]

Format of /etc/group file entry


groupname A unique character string that identifies the group to the system. password This field is always empty. Entries in this field are ignored. GID (Group ID) A unique number that identifies the group to the system. usernames A list of users who belong to the group.

09-Sep-2000

Version: 2.1

75

Protecting Files & Directories


Unix has a number of commands that enable you to control access to your files and directories. You can protect a file or directory by setting or changing its permissions, which are codes that determine the way in which anyone working on your system can use the stored data.

09-Sep-2000

Version: 2.1

76

Protecting Files & Directories


Each file and directory has nine permissions associated with it, from following three types :
r (read) w (write) x (execute)

Above three permissions occur for each of the following three classes of users:
u (file owner) g (group members of file owner) o (all others; also known as world)
09-Sep-2000 Version: 2.1 77

Protecting Files & Directories


The r permission lets users view or print the file. The w permission lets users write to (modify) the file. The x permission lets users execute (run) the file or search directories. The user/owner of a file or directory is generally the person who created it. If you are the owner of a file, you can change the file permissions with the chmod command.

09-Sep-2000

Version: 2.1

78

Protecting Files & Directories


The r permission for a directory means that its contents can be read, but not searched. Usually r and x are used together. The w permission for a directory means that files can be created or deleted. The x permission for a directory means that it can be searched.

09-Sep-2000

Version: 2.1

79

Protecting files and directories


Examples: $ ls -l total 2 -rw-r--r-- 1 larry system 101 Jun 5 10:03 file1 drwxr-xr-x 2 larry system 32 Jun 5 10:07 project $

The drwxr-xr-x indicates file type and permissions for each file. The first character indicates file type. The remaining characters are interpreted as three groups of three characters each that indicate what read (r), write (w), and execute (x) permissions are set for the owner, group, and others. If a hyphen (-) appears, the corresponding permission is not set.

09-Sep-2000

Version: 2.1

80

Protecting files and directories


The entry drwxr-xr-x indicates the following:
This is a directory (the d letter) The owner can view it, write in it, and search it (the rwx sequence) The group can view it and search it, but not write in it (the first r-x sequence) All others can view it and search it, but not write in it (the second r-x sequence)

09-Sep-2000

Version: 2.1

81

Default File Permissions


When you create a file or directory, the system automatically supplies a default permission. The following is a typical file permission : -rw-r--r- This permission specifies that the owner has read and write permissions while the group and all others have only read permission.

09-Sep-2000

Version: 2.1

82

Default File Permissions


When you create a file or directory, the system automatically supplies a default permission. The following is typical directory permission : drwxr-xr-x This permission specifies that the owner has read and write permissions while the group and all others have read and execute (search) permission.
09-Sep-2000 Version: 2.1 83

Default File Permissions


The default permission codes that your system provides relieve you from the task of specifying them explicitly every time you create a file or directory. If you want to create your own default permission codes, you must change your user mask with the umask command.

09-Sep-2000

Version: 2.1

84

Changing File Permissions


Use the chmod (change mode) command to set or change the permissions for your files and directories. Please remember that whatever restrictions you impose, the super-user can always override them. There are two ways to specify the permissions for chmod :
You can specify permissions with letters and symbols. You can specify permissions with octal numbers.
09-Sep-2000 Version: 2.1 85

Changing Permissions Using Letters


The following is the format of the chmod command when using letters and symbols: chmod userclass-operation-permission filename The userclass-operation-permission entry represents three codes that specify the user class code, operation, and permission code that you want to activate. The filename entry is the name of the file or files whose permissions you want to change.
09-Sep-2000 Version: 2.1 86

Changing Permissions Using Letters


Use one or more of the following to define a user class: u g o a User (owner) Group All others (besides owner and group) All (user, group, and all others)

09-Sep-2000

Version: 2.1

87

Changing Permissions Using Letters


Use one or more of the following to define an operation: + = Add permission Remove permission Assign permission regardless of previous setting

09-Sep-2000

Version: 2.1

88

Changing Permissions Using Letters


Use one or more of the following to define a permission: r s w x Read Set user or group ID Write Execute

09-Sep-2000

Version: 2.1

89

Changing Permissions Using Letters


Assume a file file1 that has -rw-r--r set of permissions. Now, enter the chmod command with the flags go+w. This command expands the permissions for both the group (g) and for others (o) by giving them write access (+w) to file1 in addition to the read access they already have.
09-Sep-2000 Version: 2.1 90

Changing Permissions Using Octals


You can also use octal numbers to change permissions. To use octal permission codes with the chmod command, enter the command in the following form: chmod octal-number filename The octal-number entry is a 3-digit octal number that specifies the permissions for owner, group, and others. The filename entry is the name of the file whose permissions you want to change.
09-Sep-2000 Version: 2.1 91

Changing Permissions Using Octals


An octal number corresponds to each type of permission: 4 = read 2 = write 1 = execute To specify a group of permissions, add together the appropriate octal numbers :
3 6 7 0 = = = = -wx (2 + 1) rw- (4 + 2) rwx (4 + 2 + 1) --- (no permissions)
Version: 2.1 92

09-Sep-2000

Setting Default Permissions


Every time you create a file or a directory, default permissions are established for it. These default permissions are initially established either by the operating system or the program you are running. The operating system assigns the default permission values of 777 for executable files and 666 for all other files.
09-Sep-2000 Version: 2.1 93

Setting Default Permissions


If you want to further restrict the permissions established by a program when it creates a file or directory, you must specify a user mask with the umask command. The user mask is a value that determines the access permissions when a file or directory is created.

09-Sep-2000

Version: 2.1

94

Setting Default Permissions


The umask command has following format: umask octal-number The octal-number is a 3-digit octal number that specifies the permissions to be subtracted from default permissions (777 or 666). Please note that through umask you actually specify permissions that are not to be granted.
09-Sep-2000 Version: 2.1 95

Becoming another user


The su command lets you alter your identity during a login session. A reason for altering your identity is to be able to access files that you do not own. To protect system security, you should not assume another identity without the owner's or the system administrator's permission.

09-Sep-2000

Version: 2.1

96

Becoming another user


The su command lets you log in to another user's account only if you know that user's password. The su command authenticates you and then resets both the process's user ID and the effective user ID to the value of the newly specified user ID. The effective user ID is the user ID currently in effect for the process
09-Sep-2000 Version: 2.1 97

Becoming another user


The format of the su command is: su username The username entry is the user name whose identity you want to assume. To confirm what identity you have assumed, use the whoami command. This command displays the user name of the identity you have assumed.
09-Sep-2000 Version: 2.1 98

Becoming another user


After completing your work under a new identity, you should return to your own login identity. To do so, press Ctrl/D or enter the exit command.

09-Sep-2000

Version: 2.1

99

The super-user concept


Every Unix system has a super-user who has permissions that supersede those of ordinary users. This super-user is often referred to as root. The root user has absolute power over the running of the system. This user has access to all files and all devices and can make any changes to the system. The root user is said to have super-user privileges.

09-Sep-2000

Version: 2.1

100

The super-user concept


The following is a list of tasks ordinarily performed by root users:
Edit files not usually changeable by ordinary users (for example, /etc/passwd) Change ownership and permissions of all files Execute restricted commands like mount or reboot Kill any process running on your system Add and remove user accounts Boot and shut down the system Back up the system Think properly before doing any of the above
09-Sep-2000 Version: 2.1 101

The super-user concept


To become a root user, use the su command. You must know the password for the root user. The format is: su The following example shows to become a root user :
$ su Password: ... #

The # prompt typically indicates the root user.


09-Sep-2000 Version: 2.1 102

Changing owners and groups


In addition to setting permissions, you can control how a file or directory is used by changing its owner or group. Use the chown command to change the owner of a file. Enter the command in the following form: chown owner filename

09-Sep-2000

Version: 2.1

103

Changing owners and groups


Use the chgrp command to change the group of a file. Enter the command in the following form: chgrp group filename To change the group ownership of a file, you must be a member of the group to which you are changing the file.

09-Sep-2000

Version: 2.1

104

Using Processes
A program is a set of instructions that a computer can interpret and run. While a program is running, it is called a process. Unix assigns a process identifier (PID) to every process. When a process begins executing, Unix opens three files for the process: stdin (standard input), stdout (standard output), and stderr (standard error).
09-Sep-2000 Version: 2.1 105

Using Processes
Unix allows you to run a number of different processes at the same time. These different processes can be from one or multiple users. Therefore, you do not have to enter commands one at a time at the shell prompt. Instead, you can run both foreground and background jobs simultaneously.

09-Sep-2000

Version: 2.1

106

Using Processes
Usually, when you enter a command on the command line, you wait for the results to display on your screen. Such commands are called foreground processes or jobs. However, some commands require long time. If a long-duration command runs as a foreground job, you cannot execute other commands until the current one finishes. As a result, you may want to run such command as a background job.
09-Sep-2000 Version: 2.1 107

Using Background Jobs


To run a background job, you end the command with an ampersand (&). Once a job is running in the background, you can perform additional tasks by entering other commands at your workstation.

09-Sep-2000

Version: 2.1

108

Using Background Jobs


After you create a background process, the following takes place:
The PID is displayed. In the Korn and POSIX shells or the C shell, job numbers are assigned as well. The prompt returns so that you can enter another command. In the C shell, a message is displayed when the background process is complete.

09-Sep-2000

Version: 2.1

109

New Topic

Using Regular Expressions

09-Sep-2000

Version: 2.1

110

Regular Expressions
A regular expression specifies a set of strings to be matched. It contains ordinary text characters and operator characters. Ordinary characters match the corresponding characters in the strings being compared. Operator characters specify repetitions, choices, and other features. Regular expressions fall into two groups:
Basic regular expressions Extended regular expressions
09-Sep-2000 Version: 2.1 111

Basic Regular Expressions


Basic expressions are built by concatenating simpler basic regular expressions. Ordinary characters and operator characters together make up the set of simple basic regular expressions. You can concatenate any number or combination of simple expressions to create a compound expression that will match any sequence of characters that corresponds to the concatenated simple expressions.
09-Sep-2000 Version: 2.1 112

Basic Regular Expressions - Rules


An ordinary character matches itself. A period (dot) matches any single character except the newline character. An * (asterisk) matches any number of occurrences of the preceding simple expression, including none.

09-Sep-2000

Version: 2.1

113

Basic Regular Expressions - Rules


The [chars] (Bracket expression) matches a single instance of any one of the characters within the brackets. Ranges of characters can be abbreviated by using a hyphen. For example, [0-9a-z] matches any single digit or lowercase letter. Within brackets, all characters are ordinary characters except the hyphen (when used in a range abbreviation) and the circumflex (when used as the first character inside the brackets).
09-Sep-2000 Version: 2.1 114

Basic Regular Expressions - Rules


The ^ (Circumflex) - when used at the beginning of a regular expression (or a subexpression), matches the beginning of a line (`anchors' the expression to the beginning of the line). When used as the first character inside brackets, excludes the bracketed characters from being matched. Otherwise, has no special properties. $Dollar sign - when used at the end of a regular expression, matches the end of a line (`anchors' the expression to the end of the line). Otherwise, has no special properties.
09-Sep-2000 Version: 2.1 115

Basic Regular Expressions - Rules


The \char (Backslash) - except within a bracket expression, escapes the next character to permit matching on explicit instances of characters that are usually basic regular expression operators. The expr expr ... (concatenation) - matches any string that matches all of the concatenated expressions in sequence.

09-Sep-2000

Version: 2.1

116

The grep Command


The name of the grep command is an acronym for global regular expression printer. We have already used the basic form of grep command during discussion of regular expressions. Therefore, we will not discuss this command now. See man grep for more details.

09-Sep-2000

Version: 2.1

117

Introduction to Shell

Part I

Introduction to Shell

09-Sep-2000

Version: 2.1

118

Introduction to shell
The shell is a program that acts as an interface between Unix kernel and the user. Since the shell is just a program, there are many types of shells available in a typical Unix system. Some of these are:
Bourne Shell C-shell Korn-shell Bash etc.
Version: 2.1 119

09-Sep-2000

Introduction to shell
When a user logs into Unix, the Unix system automatically executes a shell for the user as specified in the /etc/passwd file. The shell displays a prompt on the terminal, and reads a command entered by the user. Once the user enters a command, the shell interprets the command and if the command is a valid command, executes the command itself of requests the kernel to execute the command.
09-Sep-2000 Version: 2.1 120

Basic functions of a shell


Command interpretation Command execution Filename substitution I/O re-direction Piping Environmental control An interpretive programming language

09-Sep-2000

Version: 2.1

121

Command Interpretation
The shell reads the command entered by the user. The shell checks whether the command is a built-in shell command or not. If the command is a built-in shell command, the shell executes the command.

09-Sep-2000

Version: 2.1

122

Command Interpretation
If the command is not a built-in shell command, the shell looks up the list of directories specified by the PATH environment variable, and finds a program (having the same name as the command entered or looking up at an alias table) that will perform that command. If the shell cannot find the command, it displays an error message. Otherwise it executes the command.

09-Sep-2000

Version: 2.1

123

Command Execution
If the command is a built-in shell command, the shell itself performs the command. If the command is not a built-in shell command, the shell passes on the command to the kernel by:
Creating a new (child shell) process Requesting the kernel to execute the command in the new (child shell) process

09-Sep-2000

Version: 2.1

124

Filename substitution
When the user enters a command string, the shell parses the string into following components:
Command(the first part of the string) Command arguments (the subsequent parts of the string)

For example, if you enter a command-string such as ls l *.c, this string contains the ls command and two arguments -l and *.c.
09-Sep-2000 Version: 2.1 125

Filename substitution
In arguments of a command, the shell recognizes certain characters such as *, ?, [, ], and . - as special characters and expands these characters into a filename list before executing the command. To see how this works, enter following commands:
echo this is a message echo this is a message echo *
09-Sep-2000 Version: 2.1 126

Filename substitution
To see how this works, enter following commands:
echo echo echo echo echo echo echo \.* \.???????????? s* s??????.sh s[12345].sh s[1-5].sh s??????.sh

09-Sep-2000

Version: 2.1

127

I/O Re-direction
The shell provides facilities to re-direct input, output and error for a command through special characters:
Use > character to redirect outout of a command to a file. Use < character to redirect input to a command from a file. Use >> characters to append outout of a command to a file. The > and 2>&1 characters (Bourne Shell only) redirect outout and error of a command to a file.

09-Sep-2000

Version: 2.1

128

I/O Redirection-Examples
cat *.c > outfile cat *.c >> outfile cat nosuchfile 2> outfile cat * nosuchfile > outfile 2>&1 mail $user s testing IO redirection < outfile cat * nosuchfile >> outfile 2>&1

09-Sep-2000

Version: 2.1

129

Input Redirection-Special Case


The shell supports a special case of input redirection that allows you to provide the input to a command from within a shell script. For example, the cat command expects its input from the standard input (keyboard) or a file. Therefore, if you use the cat command as follows in a shell script, it will expect the input to come from the keyboard: cat > outfile
09-Sep-2000 Version: 2.1 130

Input Redirection-Special Case


In the previous example, if you wanted to provide input to the cat command from within the shell script itself, you can use << characters with a label. Consider following shell script: $ cat > outfile << _END_OF_DATA_ This data comes from a shell script This data comes from a shell script _END_OF_DATA_ $ cat outfile
09-Sep-2000 Version: 2.1 131

Using the tee command


The tee command allows you to send the output of a command to a file as well as to the standard output. Example: $ ls l | tee outfile $ cat outfile

09-Sep-2000

Version: 2.1

132

Environment Control
The shell recognizes a number of environment variables, that allow you to customize the shell environment.
Note: Shell also supports normal variables.

These variables include: PATH, PS1, PS2 etc. However, some environment variables cannot be changed. These include: HOME, USER, PWD etc.
09-Sep-2000 Version: 2.1 133

Programming Language
The shell allows you to assign values to variables. This is the most basic feature required of a programming language. The shell also provides other programming constructs including:
Condition checking Loops Input and output statements

09-Sep-2000

Version: 2.1

134

Different types of shell


Bourne Shell
Developed in 1979 by Stephen Bourne. Program name is sh. The Bourne shell is distributed as the standard shell on most Unix systems. Was the first shell developed for Unix.

09-Sep-2000

Version: 2.1

135

Different types of shell


C Shell
Developed by Bill Joy at University of California, Berkeley as part of BSD Release of Unix. Program name is csh. It is called C shell as the programming language it provides is similar to the C programming language. Provides additional features such as running a program in background, command aliasing etc.

09-Sep-2000

Version: 2.1

136

Different types of shell


Korn Shell
Developed by David Korn at Bell Labs around 1988. Program name is ksh. Incorporates most features of Bourn shell as well as C shell. Bourne shell scripts can run without modification in this shell and therefore might become a replacement for the Bourne shell.

09-Sep-2000

Version: 2.1

137

Different types of shell


Bourne Again Shell
This is a freeware from the FSF - Free Software Foundation. Developed by Brian Fox and Chet Ramey. Program name is bash. Incorporates most features of Bourn shell as well as C shell. Provides a number of enhancements such as command line editing. This is the default shell provided in Linux.

09-Sep-2000

Version: 2.1

138

Using the shell


As discussed earlier, Unix starts a shell for you when you log in. The shell displays a prompt (such as a $ prompt) and waits for you to enter a command. You can enter following types of commands:
Interactive command (such as cat, vi, ls etc.) Non-interactive command (such as a shell script) Built-in command (such as set, echo, cd, pwd)
09-Sep-2000 Version: 2.1 139

Using the shell


To find out which shell you are using, enter echo $SHELL To change your login shell to the Bourne Shell, enter: chsh /bin/sh

09-Sep-2000

Version: 2.1

140

Using the shell


To temporarily use the C Shell, enter: csh If C shell is available on your system, it will be started. You can now use C shell. To return to the original shell, enter: exit OR press CTRL-D

09-Sep-2000

Version: 2.1

141

Using the shell


To find out whether you have Korn Shell available on your system, enter: find / -name ksh -print If Korn shell is available on your system, find will show you the directory where it is stored. The output may be something like this:
/sbin/ksh
09-Sep-2000 Version: 2.1 142

Using the shell


To add the current directory in PATH, enter:
export PATH=$PATH:. (C/Korn/bash shells) PATH=$PATH:. ; export PATH (Bourne shell)

To set your terminal type to vt100, enter:


export TERM=vt100 (C/Korn/bash shells) TERM=vt100 ; export TERM (Bourne shell)

09-Sep-2000

Version: 2.1

143

Using sub-shells
A sub-shell (or a child shell) is a new shell program that you start from the current shell. The sub-shell has its own set of environment variables and does not have access to the parent shells environment. You can run a command in a sub-shell by using special characters ( ) and { ; }

09-Sep-2000

Version: 2.1

144

Using sub-shells
Examples: (cd /var ; ls l ) OR {cd /var; ls l;} Before and after executing the above commands, use pwd command to see how using a sub-shell can be of help in some situations.
09-Sep-2000 Version: 2.1 145

Next Topic

Introduction to Shell Scripting

09-Sep-2000

Version: 2.1

146

What is a shell script


A shell script is a text file containing a combination of following:
Unix commands (such as ls, cat). Shell commands (such as variable assignment) and programming constructs (such as if statement and loops)

Since a shell script is a program, it is normally assigned execute permission using the chmod command.
09-Sep-2000 Version: 2.1 147

What is a shell script


To write effective shell scripts, you need to have working knowledge of basic commands and utilities in Unix. These include:
regular expressions grep, cut, awk and sed utilities

This course does not permit time to cover the above utilities. Where relevant, we might demonstrate the use of these utilities.

09-Sep-2000

Version: 2.1

148

Executing a shell script


There are many ways of executing a shell script:
By passing the shell script name as an argument to the shell. For example:

sh script1.sh
If the shell script is assigned execute permission, it can be executed using its name. For example:

./script1.sh
09-Sep-2000 Version: 2.1 149

Executing a shell script


There are many ways of executing a shell script:
If the shell script has execute permission and is stored in a directory listed in PATH, it can be executed using its name. For example:
script1.sh

If the shell script has execute permission and is stored in a directory listed in PATH, it can be executed using the dot command. For example:
. script1.sh
09-Sep-2000 Version: 2.1 150

Sample Shell Script


#! /bin/sh # # The above line has a special meaning. It must be the # first line of the script. It says that the commands in # this shell script should be executed by the Bourne # shell (/bin/sh). # --------------------------------------------------------------echo Hello $USER. echo I hope you like working with shell scripts.. # ---------------------------------------------------------------

09-Sep-2000

Version: 2.1

151

Shell Variables
The shell provides facility to define normal and environment variables. A normal variable can be only used in the shell where it is defined. An environment variable can be used in the shell where it is defined, plus any child shells invoked from that shell. Therefore, if you define an environment variable, it can be used within a shell script.
09-Sep-2000 Version: 2.1 152

Using Normal Variables


To define a normal variable, use following syntax: variable_name=value Examples: $ x=10 $ textline_1=This line was entered by $USER $ textline_2=This line was entered by $USER 09-Sep-2000 Version: 2.1 153 $ allusers=`who` $ countusers=`who | wc l`

Using Normal Variables


Having defined above variables, you can use the echo command to display the value of each variable:
$ echo $ echo $ echo $ echo $ echo $x $textline_1 $textline_2 $allusers $countusers

09-Sep-2000

Version: 2.1

154

Using Normal Variables


To reset a variable, use
$ var_name= $ var_name=# $ var_name=

OR OR

All the three commands are equivalent.

09-Sep-2000

Version: 2.1

155

Using Environment Variables


To define an environment variable, use following syntax:
variable_name=value export variable_name

Examples:
$ x=10; export x $ allusers=`who` ; export allusers

09-Sep-2000

Version: 2.1

156

Built-in Environment Variables


Korn shell provides a number of built-in environment variables. These include:
PATH HOME PWD SHELL TERM MAIL USER LOGNAME

09-Sep-2000

Version: 2.1

157

Built-in Environment Variables


Each of the built-in environment variables contains information assigned by the shell. Some of these environment variables (such as PATH, TERM, MAIL etc.) can be modified. The other environment variables (such as USER, SHELL, LOGNAME, PWD etc.) can not be or should not be modified.

09-Sep-2000

Version: 2.1

158

Shell meta-characters
The Bourne Shell recognizes a number of metacharacters. Each meta character can represent zero or more ordinary characters. These meta characters are used in:
Filename expansion Variable assignment Forming regular expressions etc.

09-Sep-2000

Version: 2.1

159

Shell meta-characters
These meta-characters are:
Asterisk - * Question Mark - ? Square brackets [ and ] Single quote Double quote Back quote - ` Back slash - \

09-Sep-2000

Version: 2.1

160

Shell meta-characters
Examples:
$ x=* ; echo $x $ x=?????? ; echo $x $ x=[a-p]????? ; echo $x $ x=$USER sold the book for $10 ; echo $x $ x=$USER sold the book for $10 ; echo $x $ x=$USER sold the book for \$10 ; echo $x $ x=`who` ; echo Current users = $x

09-Sep-2000

Version: 2.1

161

Shell meta-characters
Examples:
$ x=* ; echo $x $ x=?????? ; echo $x $ x=[a-p]????? ; echo $x $ x=$USER sold the book for $10 ; echo $x $ x=$USER sold the book for $10 ; echo $x $ x=$USER sold the book for \$10 ; echo $x $ x=`who` ; echo Current users = $x

09-Sep-2000

Version: 2.1

162

Passing parameter to script


You can pass parameter to a shell script by entering the parameters after the name of the shell script. Within the shell script, you can refer to the parameters through variables $1 thru $9. If you need to use more than 9 parameters, you can use the shift command within the shell script to refer to additional parameters.
09-Sep-2000 Version: 2.1 163

Passing parameter to script


Consider following shell script: ----------------------script2.sh-------------------------echo Total parameters entered: $# echo First parameter is : $1 echo Last parameter is : $$# ----------------------------------------------------------- Execute the above script using the script2.sh these are the parameters command.
09-Sep-2000 Version: 2.1 164

Passing parameter to script


The shell parameters are passed as strings. If you want to pass a string containing multiple words as a single parameter, you must enclose the string within quotes. For example, $ script2.sh P1 P2 P3

09-Sep-2000

Version: 2.1

165

Doing arithmetic operations


You must use the expr command to perform arithmatic operations in Korn shell. Consider following shell script: ----------------------script3.sh-------------------------echo This will not work: \$1 + \$2 = $1 + $2 echo This will work: \$1 + \$2 = `expr $1 + $2` -----------------------------------------------------------09-Sep-2000 Version: 2.1 166

Doing arithmetic operations


You can use normal operators with the expr command. For example, $number_1 $number_2 $number_3 $number_4 $number_5 = = = = = `expr `expr `expr `expr `expr $1 $1 $1 $1 $1 + $2` - $2` / $2` * $2` % $2`

09-Sep-2000

Version: 2.1

167

Condition Checking In Scripts


Korn shell provides the if command to test if a condition. The general format of this command is:
if condition then command fi

The condition is typically formed using the test command.


09-Sep-2000 Version: 2.1 168

Using the test command


The general syntax of test command is: test <expression> The expression can be formed using a combination of shell variables and the operators supported by the test command. These operators provide facility to compare numbers, string and logical values, file types and file access modes.

09-Sep-2000

Version: 2.1

169

Using the test command


To compare two integers using test following operators are available: -eq (equal to) -ne (not equal to) -lt (less than) -le (less than or equal to) -gt (greater than) -ge (greater than or equal to)

09-Sep-2000

Version: 2.1

170

Using the test command


Please note that you can only compare two integers using the test command. The syntax for this comparison is: test integer1 operator integer2 OR [ integer1 operator integer2 ]

09-Sep-2000

Version: 2.1

171

Using the test command


To compare two strings using the test command, following operators are available:
string1 == string2 (equal to) string1 != string2 (not equal to) string1 (string is not NULL) -n string1 (string is not NULL and exists) -z string1 (string is NULL and exists)

09-Sep-2000

Version: 2.1

172

Using the test command


The syntax for this string comparison is: test string1 operator string2 OR [ string1 operator string2 ] OR test operator string OR [ operator string ]

09-Sep-2000

Version: 2.1

173

Using the test command


To check a file type/access permissions using the test command, following operators are available:
-s file (file is not empty) -f file (file is not a directory) -d file (file is a directory) -r file (file is readable) -w file (file is write-able) -x file (file is executable)

09-Sep-2000

Version: 2.1

174

Using the test command


To check a file type/access permissions using the test command, following operators are available:
-b file (file is a block device) -c file (file is a character device) -p file (file is a named pipe) -g file (file has sticky bit set) -u file (file has setuid bit set) -t file_des (file descriptor is standard output)

09-Sep-2000

Version: 2.1

175

Using the test command


The syntax for this file checks is: test operator filename OR [ operator filename ]

09-Sep-2000

Version: 2.1

176

Combining conditions
It is possible to combine conditions by using following operators:
-a (logical AND operator) -o (logical OR operator) ! (logical NOT operator)

09-Sep-2000

Version: 2.1

177

Combining conditions
The syntax for this is: test expression_1 a expression _2, OR [expression _1 a expression _2 ] test expression_1 o expression _2, OR [expression_1 o expression_2 ] test ! expression _1, OR [ ! expression _1]
09-Sep-2000 Version: 2.1 178

Checking multiple conditions


The complex form of if statement is as follows: if condition_1 then command elif condition_2 then command else command fi
09-Sep-2000 Version: 2.1 179

Using the case statement


Korn shell also provides a case statement for this purpose. The syntax is: case value in pattern_1) command command ;; pattern_n) command command ;; *) command command ;; esac 09-Sep-2000 Version: 2.1

180

Using the case statement


The value can be a shell variable. The patterns pattern_1 thru pattern_n can be simple string values or regular expressions.

09-Sep-2000

Version: 2.1

181

Using the for loop


The Korn shell provides a for loop. The syntax of this loop is:
for variable in list do command command done

09-Sep-2000

Version: 2.1

182

Another example
----------------------script4.sh--------------------------

#! /bin/sh usernames=`who | awk {print $1}` echo Total users logged in = $#usernames # for user in ${usernames} do echo $user done -----------------------------------------------------------09-Sep-2000 Version: 2.1 183

Using the while loop


The Korn shell provides a while loop. The syntax of this loop is:
while condition do command command done

09-Sep-2000

Version: 2.1

184

Using shell functions


Shell functions are one of the most useful features of the Korn shell. Once a function is defined to the shell, it is maintained in memory, so disk i/o is reduced and execution is faster than a traditional shell script. A function can also be called several times in your script, so total lines of code are reduced. A shell function can be defined in the .profile file, or in a separate script file.
09-Sep-2000 Version: 2.1 185

Using shell functions


Shell functions are a way to group commands for later execution using a single name for the group. They are executed just like a "regular" command. Shell functions are executed in the current shell context; no new process is created to interpret them. Functions are declared using this syntax: [ function ] name () { command-list; }
09-Sep-2000 Version: 2.1 186

Using shell functions


[ function ] func_name () { commandlist; } The above defines a shell function named name. The reserved word function is optional. If the function reserved word is supplied, the parentheses are optional. The body of the function is the command-list between { and }. This list is executed whenever func_name is specified as the name of a command.
09-Sep-2000 Version: 2.1 187

Using shell functions


[ function ] func_name () { commandlist; } The exit status of a function is the exit status of the last command executed in the body. When a function is executed, the arguments to the function become the positional parameters during its execution. The special parameter `#' that expands to the number of positional parameters is updated to reflect the change. Positional parameter 0 is unchanged.
09-Sep-2000 Version: 2.1 188

Using shell functions


[ function ] func_name () { commandlist; } If the built-in command return is executed in a function, the function completes and execution resumes with the next command after the function call. You can also provide an integer argument to the return statement.
09-Sep-2000 Version: 2.1 189

Using shell functions


[ function ] func_name () { commandlist; } When a function completes, the values of the positional parameters and the special parameter `#' are restored to the values they had prior to the function's execution. If a numeric argument is given to return, that is the function's return status; otherwise the functions's return status is the exit status of the last command executed before the return.
09-Sep-2000 Version: 2.1 190

Using shell functions


[ function ] func_name () { commandlist; } Variables local to the function may be declared with the local built-in variable syntax. These variables are visible only to the function and the commands it invokes. Functions may be recursive. No limit is placed on the number of recursive calls.
09-Sep-2000 Version: 2.1 191

Shell functions - Example


# Function net_on returns 0 if SQL*Net processes are found # and 1 if they are not found. No arguments required. # net_on () { sleep 10 if ps -f -u oracle | grep -v grep | grep tns > /dev/null then return 0 else return 1 fi }
09-Sep-2000 Version: 2.1 192

Shell functions - Example


# Function dbs_on takes one argument (SID) and returns 0 if # related database processes are found and 1 if they are not. # dbs_on () { sleep 10 if ps -f -u oracle | grep -v grep | grep ora_ | grep "$1" > /dev/null then return 0 else return 1 fi }

09-Sep-2000

Version: 2.1

193

Shell functions - Example


#!/bin/sh # # Initialize shell functions . $HOME/bin/shell_functions # Make sure that user specified an SID value. if [ -z "$1" ] then echo "dbs_start: `date '+%H:%M:%S`: Error: No database specified." exit 2 fi (continued...)
09-Sep-2000 Version: 2.1 194

Shell functions - Example


(continued from previous slide...)
# Check to see if the specified database is already running. if dbs_on "$1" then echo "dbs_start: `date '+%H:%M:%S`: $1 Database already started." exit fi

(continued...)
09-Sep-2000 Version: 2.1 195

Shell functions - Example


(continued from previous slide...)
# Check to see if SQL*Net Listener is running if net_on then echo "dbs_start: `date '+%H:%M:%S`: SQL*Net Listener already on." else echo "dbs_start: `date '+%H:%M:%S`: SQL*Net Listener not running." lsnrctl start

(continued...)
09-Sep-2000 Version: 2.1 196

Shell functions - Example


(continued from previous slide...)
if net_on then echo "dbs_start: `date '+%H:%M:%S`: SQL*Net Listener started." else echo "dbs_start: `date '+%H:%M:%S`: SQL*Net Listener not started." exit 2 fi fi

(continued ...)
09-Sep-2000 Version: 2.1 197

Shell functions - Example


(continued from previous slide...)
# Set environment variables ORACLE_SID=$1 export ORACLE_SID # Start the specified database using Server Manager in line mode. svrmgrl << ENDMGR connect internal startup exclusive open ENDMGR

(continued ...)
09-Sep-2000 Version: 2.1 198

Shell functions - Example


(continued from previous slide...)
# Check to make sure database starts correctly. if dbs_on "$1" then echo "dbs_start: `date '+%H:%M:%S`: $1 Database started successfully." else echo "dbs_start: `date '+%H:%M:%S`: Error: $1 Database could not start." exit 2 fi

(end of script...)
09-Sep-2000 Version: 2.1 199

Debugging Shell Scripts


At times you may need to debug a program to find and correct errors. Two options to the sh command can help you debug a program: sh -v shell_script_name The -v (verbose) option prints the shell input lines as they are read by the system.

09-Sep-2000

Version: 2.1

200

Debugging Shell Scripts


sh -x shell_script_name The -x (execute) option prints the commands and their arguments as they are executed. To try these two options, create a shell program that has an error in it.

09-Sep-2000

Version: 2.1

201

Debugging Shell Scripts


For example, create a file called bug that contains the following list of commands:
$ cat bug today=`date` echo enter person read person mail $1 Hello $person , The system will not be available between 3 and 5 PM today. $today. From System Administrator $

09-Sep-2000

Version: 2.1

202

Debugging Shell Scripts


The corrected script is as follows:
$ cat bug today=`date` echo enter person read person mail $1 << _DATA_ Hello $person , The system will not be available between 3 and 5 PM today. $today. From System Administrator _DATA_ $

09-Sep-2000

Version: 2.1

203

New Topic

System Programming

09-Sep-2000

Version: 2.1

204

System Programming Basics


System Programming means writing C (or C++) programs that use Unix system calls. Therefore, you should know the difference between a system call and a library routine. Most (not all) system calls return 0 on success and -1 on failure. Your program should check whether a system has failed, and if it finds that the system call has failed, it should obtain more information on why the system call has failed.

09-Sep-2000

Version: 2.1

205

System Programming Basics


When a Unix system call fails, it sets an error code value in an extern int variable called errno, which indicates the reason for failure. Your program can also display the error message associated with the error code (stored in errno) by using the perror function. Please note that you should call this function only if the system call has failed.
09-Sep-2000 Version: 2.1 206

The Role Of Standard C Library


The C compiler automatically links your program with /usr/lib/libc.a library. Therefore it is called standard C library. However, if you create your own library and want to link a C program with your library, you must use -l option to the cc command and provide the name of your library.

09-Sep-2000

Version: 2.1

207

The Role Of Standard C Library


The standard C library contains:
Object code of all library routines such as printf, scanf, getchar etc. Object code of system call wrapper functions. Each wrapper function invokes a system call. The actual system call is a part of Unix kernel.

09-Sep-2000

Version: 2.1

208

Next Topic

File Handling System Calls

09-Sep-2000

Version: 2.1

209

Ashwin: Ashwin: Start from here Start from here 2marrow 2marrow

File Handling

Topics
Creating files Reading and writing files Getting file statistics Sharing and locking files Reading directories

09-Sep-2000

Version: 2.1

210

Unix Files
A file is a stream (series) of bytes. A file does not have any structure (such as fixed-length records, indexedetc.). There is no concept of a record as far as Unix is concerned. If you want to write an application that uses records, you need to implement this feature yourself. There is no system call to delete a part of a file (a record from a file). If you need this feature, you need to implement it yourself.
09-Sep-2000 Version: 2.1 211

Creating a file
To create a file, a process can use creat( ) or open( ) system calls. The creat( ) system call has following prototype: int creat( const char *pathname, // the name and directory // where you want the file mode_t mode // access permissions Version: 2.1 09-Sep-2000 212 );

Creating/Opening a file
The open( ) system call has following prototype:
int open( const char *pathname, int flags, mode_t mode ); // the pathname and // the mode in which // access permissions

The open( ) system, if successful, returns a descriptor (which is actually a number) to refer to the open file. The process then uses this descriptor to read/write etc. from the file.

09-Sep-2000

Version: 2.1

213

Creating/Opening a file
The flags parameter can be:
O_CREAT O_RDONLY O_WRONLY O_RDWR O_APPEND O_EXCL ( used with O_CREAT) - create a file only if it does not exist

The mode parameter indicates octal permissions to be assigned to the file. Only used this parameter when the flags contains O_CREAT.
09-Sep-2000 Version: 2.1 214

Creating a file
Try the following Try:

Change myfile.txt to /myfile.txt and run the int fd; fd = creat( myfile.txt, 0644); program
if ( -1 == fd ) { perror (Cannot create file); } else { printf(File created); }

09-Sep-2000

Version: 2.1

215

Opening an existing file


Try the following (include another header file: <fcntl.h>) Try:
int fd; fd = open( myfile.txt, O_APPEND);

Change myfile.txt to notmyfile.txt and run the program

if ( -1 == fd ) { perror (Cannot open file); } else { printf(File openeddescriptor is: %d \n, fd ); }


09-Sep-2000 Version: 2.1 216

Creating a file using open


Try:

Try the following (include another header file: Change O_RDWR to O_RDWR | O_EXCL and <fcntl.h>)
run the program
int fd; fd = open( newfile.txt, O_CREAT | O_RDWR, 0644 ); if ( -1 == fd ) { perror (Cannot create file); } else { printf(File createddescriptor is: %d \n, fd ); }
09-Sep-2000 Version: 2.1 217

Reading from a file


To read from a file, a process uses the read( ) system call, which has following prototype:
#include <unistd.h> ssize_t read( int fd, // file descriptor void *buf, // address of the buffer to store data size_t count // length of the buffer );

The read( ) system call, if successful, returns the number of bytes read from the file. If it encounters end-of-file, it returns 0.
09-Sep-2000 Version: 2.1 218

Reading from a file


Add following to program that opened the file: Try: int bytes; buffer[bytes] = \0; char buffer[64]; /* the existing code goes here */ bytes = read( fd, buffer, sizeof(buffer) ); if ( -1 == bytes ) { perror(Cannot read from file); } printf(Read %d bytes from file..\n, bytes); printf(Data is: %s \n, buffer);
09-Sep-2000 Version: 2.1

Add following before last printf:

219

Writing to a file
To write to a file, a process uses the write( ) system call, which has following prototype: #include <unistd.h> ssize_t write( int fd, // file descriptor void *buf, // address of the buffer size_t count // length of the buffer ); The write( ) system call, if successful, returns the number of bytes written to the file. If it 09-Sep-2000 Version: 2.1 encounters error, it returns -1.

220

Writing to a file
Try:

Add following to last program: Change sizeof to strlen


and run the program

int bytes; Try-2: char buffer[64]; Change fd to 1 and run the /* the existing code goes here */ program printf(Enter data:); Try-3: gets(bufffer); Change fd to bytes = write ( fd, buffer, sizeof(buffer) 0);and run the program if ( -1 == bytes ) { perror(Cannot write to file); } printf(Written %d bytes to file..\n, bytes);
09-Sep-2000 Version: 2.1 221

Closing a file
To close a file, a process uses the close( ) system call, which has following prototype: #include <unistd.h> int close( int fd, );

// file descriptor

09-Sep-2000

Version: 2.1

222

Lab 1 Reading the file


Write a C-program to
Accept a file name from command line parameter (use argc and argv parameter to main - argv[1] will be the filename) Open the file in readonly (O_RDONLY) mode Read 80 characters at a time from the file, until the end of the file is detected (the read system call returns 0 when end of file is detected). Display each line as it is read Close the file when end-of-file is reached

09-Sep-2000

Version: 2.1

223

Additional system calls


Unix provides following additional calls for files:
lseek(), to move within a file unlink(), to delete a file stat(), to obtain information about a file fcntl(), to change attributes of a file (including lock and unlock) flock()/lockf() to lock a file dup()/dup2() to duplicate a file descriptor

09-Sep-2000

Version: 2.1

224

Moving within a file


The lseek() call has following prototype
#include <unistd.h> off_t lseek( int fildes, // file descriptor off_t offset, // the byte offset where to move int whence // how to interpret the offset // SEEK_SET - w.r.t start of file // SEEK_CUR - w.r.t current position // SEEK_END - w.r.t end of file );

09-Sep-2000

Version: 2.1

225

Moving within a file


The lseek() calls offset parameter can be a positive or a negative value. If successful, lseek( ) returns the new position in the file (where file pointer is pointing to). It is also possible to move beyond end of file !!!, but not possible to move before start of file -)))))

09-Sep-2000

Version: 2.1

226

Obtaining information of a file


To obtain information about a file, you can use stat() or fstat() system calls
int stat( const char *file_name, // pathname of the file struct stat *buf ); int fstat( int filedes, struct stat *buf ); // file descriptor // pointer to a variable of // type struct stat

09-Sep-2000

Version: 2.1

227

Changing/getting file attributes


To change/get attributes of a file, you can use the fcntl() system call
int fcntl(int filedes, int cmd ); int fcntl(int filedes, int cmd long arg ); // file descriptor // command such as F_GETOWN

// file descriptor // command such as F_SETOWN // argument to command

09-Sep-2000

Version: 2.1

228

Deleting a file
To remove a file name, you can use unlink() system call. Please note that this call removes a name and decrements the link count. If all the names are removed (link count becomes zero), then the file is physically deleted.
int unlink(const char *pathname // pathname of file to be deleted );

09-Sep-2000

Version: 2.1

229

Locking a file
To lock/unlock a file, you can use the flock() or fcntl() system calls:
#include <sys/file.h> int flock( int fd, // file descriptor int operation // type of lock ) The lock types (operation) are: Shared (LOCK_SH) or Exclusive ( LOCK_EX)

09-Sep-2000

Version: 2.1

230

Locking a file
To lock/unlock a file, you can use flock() or fcntl() system calls: #include <sys/file.h> int flock( int fd, descriptor int operation )
The lock types (operation) are:
Unlock (LOCK_UN) or Donot wait/block for lock ( LOCK_NB)
09-Sep-2000 Version: 2.1 231

// file // type of lock

Locking a file
Example of using flock() int main() { int fd, status; fd = open( sharedfile.txt, O_RDWR); status = flock( fd, LOCK_EX | LOCK_NB ); if ( -1 == status ) { perror(Cannot lock file); }
Version: 2.1

09-Sep-2000

232

Locking a file
Example of using fcntl() to lock a file int fd, status; struct flock lockinfo; fd = open( sharedfile.txt, O_RDWR); lockinfo.l_type = F_WRLCK; // write lock lockinfo.l_whence =SEEK_SET ; // from BOF lockinfo.l_start = 0; // start from BOF lockinfo.l_len = 100; // lock 100 bytes
09-Sep-2000 Version: 2.1 233

status = fcntl( fd, F_SETLKW , &lockinfo );

Duplicating a file descriptor


You can use the dup() or dup2( ) system call to duplicate an existing file descriptor. If you duplicate an existing file descriptor, you will have two descriptors referring to the same open file. And then you can do magic...

09-Sep-2000

Version: 2.1

234

Duplicating a file descriptor


Try this in a program where a file is open for writing: /* after existing code */ close(1); dup(fd); printf(This should appear on screen.\n);

09-Sep-2000

Version: 2.1

235

Duplicating a file descriptor


If you duplicate an existing file descriptor, you will make that existing file descriptor to also refer to another file. For example, if you have file descriptor 4 referring to use_dup.txt and if you duplicate that descriptor, another descriptor (such as file descriptor 1) may also refer to the same file (use_dup.txt).

09-Sep-2000

Version: 2.1

236

Duplicating a file descriptor


This happens because of the close system call that is used before the call to dup, to close descriptor 1. The dup system call returns the lowest available file descriptor. Since descriptor 1 (which refers to standard output, or screen) was closed, it is the lowest available file descriptor and is returned by dup.
09-Sep-2000 Version: 2.1 237

Duplicating a file descriptor


Therefore, fd as well as 1 refer to the same file. When you use printf in your program, it writes its data to standard output (descriptor 1). Since descriptor 1 also refers to the same file, the output of printf goes to the same file. This means that the standard output refers to another file. This is what the shell does when you use a command such as ls -l > outfile.
09-Sep-2000 Version: 2.1 238

Duplicating a file descriptor


The shell uses the dup/dup2 calls to implement:
input/output redirection piping (in combination with the pipe() system call)

09-Sep-2000

Version: 2.1

239

Standard File Descriptors


Every Unix process gets three standard file descriptors, that are always open:
descriptor 0, means standard input (stdin) and refers to the keyboard descriptor 1, means standard output (stdout) and refers to the monitor screen descriptor 2, means standard error (stderr) and refers to the monitor screen

09-Sep-2000

Version: 2.1

240

Reading Directories
To read directories, following calls are available:
opendir readdir or scandir rewinddir/seekdir closedir

09-Sep-2000

Version: 2.1

241

Reading Directories
To read directories, following calls are available:
Include <dirent.h> header file. Declare a variable DIR *d; Declare a variable struct dirent *dp; Use opendir() function to open a directory. In a while (1) loop, use readdir() function to read each directory entry. Break from the loop and close the directory when readdir returns NULL. Use printf to display following from each entry (the dp variable):
d_ino (print using %d) d_name (print using %s)
09-Sep-2000 Version: 2.1 242

Lab 2 Using Files


Write a C program that maintains a database (which is a file) of your training schedule. This database contains following information:
course name, upto 40 characters start date , upto 12 characters end date , upto 12 characters faculty , upto 16 characters

The program will use following system calls:


open, read, write, lseek, close
09-Sep-2000 Version: 2.1 243

Lab 2 Using Files


The training schedule data is stored in a structure that contains following members
schedule ID (a number, starting from 1) course name, upto 40 characters start date , upto 12 characters end date , upto 12 characters faculty , upto 16 characters delete flag (0-not deleted or 1-means deleted)

09-Sep-2000

Version: 2.1

244

Lab 2 Using Files


The program will provide options to :
add a new schedule record query an existing schedule record, by schedule ID view all schedule records update an existing schedule record , by schedule ID delete an existing schedule record , by schedule ID

09-Sep-2000

Version: 2.1

245

Using debugger
Each Unix system may provide a different debugger. Most Unix systems support dbx. Linux provides the gdb debugger. To use the debugger:
compile your program with -g option to the cc command. Invoke the debugger using gdb <program_name>

09-Sep-2000

Version: 2.1

246

New Topic

Process Management System Calls

09-Sep-2000

Version: 2.1

247

Process Management
Topics
Creating a new process Running a new program in a process Waiting for child process to exit Collecting exit status from child process Accessing process environment Changing process environment Process relationships (Process Groups) Redirecting output of a process to a file Redirecting input to a process from a file

09-Sep-2000

Version: 2.1

248

The Process Concept


A process (also called a task) is used by Unix to run a program. You can say that a process describes the attributes of a running program. Since a running program has a number of dynamic attributes, Unix continuously stores the attributes of a running program for every process.
09-Sep-2000 Version: 2.1 249

Ashwin: Ashwin: Satrt 4m here 24rdrd Satrt 4m here 24 april 2002 april 2002

The Process Concept

A number of attributes of a running program dynamically change. Some of these are:


Program Counter Stack Pointer CPU Registers Memory locations referenced by the program And more. (more about this in Unix Internals training program).

09-Sep-2000

Version: 2.1

250

The Process Concept


A number of attributes of a running program DO NOT NORMALLY change. Some of these are:
Process ID (when a program runs, it is given a ID) Parent Process ID (the Process ID of the process that started this program) Real User ID (the User ID of the user that started this program) Real Group ID (the Group ID of the user that started this program)

09-Sep-2000

Version: 2.1

251

Reading Process Attributes


Some of the process attributes (such as Process ID, Parent Process ID, Real User ID, Real Group ID) can be read using Unix system calls. Some of the process attributes (such as Real User ID, Real Group ID, Effective User ID, Effective Group ID) can be changed using Unix system calls.

09-Sep-2000

Version: 2.1

252

Creating a new process


A process uses the fork() system call to create a new process. This means that to create a new process you always need a process. In Unix, all processes are created using the fork() system call, with the exception of the init process (which has a PID of 1), which is hand-crafted (meaning it is not created using the fork() system call, but by another method).

09-Sep-2000

Version: 2.1

253

Creating a new process


When you use the fork() system call, one more process will be created if fork() is successful. All statements after the fork() system call in your program are executed by two processes the original process that used fork(), plus the new process that was created by fork( ).

09-Sep-2000

Version: 2.1

254

Creating a new process


To change this behavior, the fork system call has been designed to return a different value to each process.
The fork() returns 0 in the new (child) process The fork() returns >0 (child processs PID) in the parent process, meaning the process that used the fork( ) system call

Note: fork( ) also returns -1 if it cannot create a process


09-Sep-2000 Version: 2.1 255

Creating a new process


When you use the fork() system call in a Cprogram, you check the return value of the fork() and then force the child process and parent process to execute a different set of statements
if it 0, then it is child process if it is >0 then it is parent process

09-Sep-2000

Version: 2.1

256

Running a new program in a process


To run a new program in a process, you use one of the exec family of calls (such as execl) and specify following:
the pathname of the program to run the name of the program each parameter to the program (char *)0 as the last parameter to specify end of parameter list

09-Sep-2000

Version: 2.1

257

Running a new program in a process


Therefore, to run a new program in the child process:
check that fork() returns 0 (it is a child process). use one of the exec calls (such as execl( ) )to run a new program in the child process.

09-Sep-2000

Version: 2.1

258

Waiting for child process to exit


A parent process can use the wait( ) system call to wait for the exit of ANY child process. When the parent process uses the wait( ) system call, it will be suspended until one of its child processes (not a specific child process) exits. Once a child process exits, the parent process comes out of the wait( ) system call.

09-Sep-2000

Version: 2.1

259

Waiting for child process to exit


A parent process can also use the wait( ) system call to collect the exit status of the child process. A child process can return an exist status to the parent by using the int parameter to the exit( ) system call. To wait for a specific child process to exit, a parent process can use waitpid( ) system call.
09-Sep-2000 Version: 2.1 260

Waiting for child process to exit


The waitpid() call has following prototype: pid_t waitpid(pid_t pid, int *status, int options); The parent will pass the PID of the child in the pid parameter to indicate a specific child process.

09-Sep-2000

Version: 2.1

261

Lab 3 Getting Process IDs


Write a C program that displays the following information about the current process:
Process ID (use getpid() system call) Parent process ID ( use getppid() system call) Real user ID and group ID ( use getuid()/getgid() system call) Effective user ID and group ID ( use geteuid()/getegid() system call)

09-Sep-2000

Version: 2.1

262

Lab 4 Creating Processes


Write a C program that does the following :
Creates a process ( use fork() system call ) The child process displays following message and runs ps -l command (use execl() system call):
Child <PID> : Trying to run the ps command

The parent process waits for child process to finish the ps -l command (use wait() system call) and displays following message ( and the exit status ? )
Parent <PID> : Finished running the ps command

09-Sep-2000

Version: 2.1

263

Lab 5 Accessing Environment


Write a C program that displays a list of all environment variables in the following format:

Environment Variable Value --------------------------------------------------------HOME /home/user1 SHELL /bin/bash


Use extern variable environ to access the above list and display. See man environ for details.
09-Sep-2000 Version: 2.1 264

Process Relationships
When a child process (the program running in the child process) exits, it returns a status to the parent process. Therefore, when a child process is exiting, the parent process should be ready to collect the exit status. If the parent process is not ready to collect the exit status (if it is busy or suspended), the child process will not be able to exit. Such a child process is known as a zombie process.
09-Sep-2000 Version: 2.1 265

Process Relationships
Unix always ensures that a process has a parent process. If the parent process exits (while the child process is alive), Unix makes another process (the init process) as the parent process of the child that is alive. However, since the original parent process terminated, such a child process is called an orphan.

09-Sep-2000

Version: 2.1

266

Lab 6 Zombie Process


Write a C program that creates a zombie process. The zombie process should be destroyed after 15 seconds. Use the fork() and sleep() routines in this program. Use the ps -l command to check that the process has become a zombie process.

09-Sep-2000

Version: 2.1

267

Process Groups
Each Unix process belongs to a process group. Unix uses process groups to distribute signals as well as for job control. By default, a process inherits its process group from the parent process. However, a process can change its process group, or create a new process group at anytime by using the setprgp() system call.
09-Sep-2000 Version: 2.1 268

Redirecting output
Unix opens three files for every Unix process. These files are identified by file descriptors 0 (stdin) , 1 (stdout) and 2 (stderr). A process can close the standard output using the close(1) system call, and use the dup() system call to redirect output to a file. The file must have been opened earlier (in write mode) using the open() system call.

09-Sep-2000

Version: 2.1

269

Redirecting input
Unix opens three files for every Unix process. These files are identified by file descriptors 0 (stdin) , 1 (stdout) and 2 (stderr). A process can close the standard input using the close(0) system call, and use the dup() system call to redirect output from a file. The file must have been opened earlier (in read mode) using the open() system call.

09-Sep-2000

Version: 2.1

270

Lab 7 Output Redirection


Write a C program that :
Use the open system call to create a new file. The filename is passed as an argument to the program. Closes standard output and duplicates the file descriptor returned in previous step. In a for loop that has 10 iterations, displays a suitable message. Closes the file

Run the program and observe the output as well as contents of the newly created file.
09-Sep-2000 Version: 2.1 271

S-ar putea să vă placă și