Você está na página 1de 98

17 September 2010

TCS Internal
Advanced Unix
TCS Internal
17 September 2010
TCS Internal
2
Course Outline
After going through this part of the course, you would be familiarized with
Communication tools
Shell scripting
System calls
Inter-process communication
17 September 2010
TCS Internal
3
UNIX Communication Tools
write
mesg
talk
mail
wall
finger
ftp
telnet
17 September 2010
TCS Internal
4
The write Command
It lets you have a two-way communication with any person who is currently logged in.
One user writes his message and then waits for the reply from the other. The
conversation continues until one or both the users decide to terminate it:
$ write ntpuser1
Have you completed exercise 1?
^d # Ctrl-d is the end of file from terminal
Here ntpuser1 is the login-id of the recipient as argument and the text of the message
comes from the standard input.
It is equally possible to store this message in a file mymsg and apply input redirection:
$ write ntpuser1 < mymsg
The message appears on ntpuser1s terminal provided he is logged in, else sender gets
an error message response. If the recipient is logged in more than one terminal, the
message is sent to the lowest numbered terminal unless you have provided the terminal
numbers as more arguments:
17 September 2010
TCS Internal
5
The write mesg Commands
Once into the write program, you can execute any UNIX command by preceding it with the
operator !. The command output is not transmitted.
Since write ties you up in this interactive (and slow) conversation, UNIX offers the mail
command to permit deferred communication so that your own work does not get affected.
Normally, you are not permitted to receive messages from other users for security
considerations. Such permissions are granted by the mesg command to be discussed next.
The mesg command can be used to prevent other people from writing to your terminal as
follows:
$ mesg n # default mode is y
You can know the status of your terminal by typing:
$ mesg # y or n will be the response
The message of today is stored in a file /etc/motd.
17 September 2010
TCS Internal
6
Administrator can broadcast messages to all users (users can also do so on some
systems):
wall <Enter>
Machine will be shut down in 10 minutes. So log out, please!
^d # Ctrl-d is the end of file from terminal
wall
17 September 2010
TCS Internal
7
The talk Command
The write tool was nice for communication one at a time. Simultaneous typing is
enabled by the talk tool. Entering mesg n similarly just turns talk off.
talk is an interactive communication tool that enables you to have an actual
conversation in real-time mode with a user who has to be logged in.
You get an appropriate message if someone does not want to talk to you, else your
terminal shows a divided screen. You can type your message on the top half of the
screen and it appears verbatim on the other terminal at the bottom half of the screen.
Both users can type messages simultaneously. The connection can be closed by
entering <Ctrl-C>.
17 September 2010
TCS Internal
8
The mail Command
Electronic mail (E-mail) has taken the world by storm. It is stored in a file called system
mail in a mailbox that has the same name as that of the user. For example, the user
ashoks mailbox under Linux is /var/spool/mail/ashok.
17 September 2010
TCS Internal
9
The mail Commands
Pine, a trademark of the University of Washington, stands for Program for Internet
News and E-mail. Pine is also capable of sending documents and graphics.
Like write, mail uses standard input but is capable of input redirection from a file.
The mail program when used for the purpose of viewing the mail, features a prompt
(&). There are a whole lot of internal commands that you can enter at this prompt to
save, delete, ignore, reply the mail that you have received. On-line help can be sought
by typing ? at the prompt.
17 September 2010
TCS Internal
10
The mail - Internal Commands
All the available options in the Mail can be listed by typing a ? after the &. The listed
options are:
t <message list> - type messages
n - go to and type next message
e <message list> - edit messages
f <message list> - give headlines of messages
d <message list> - delete messages
s <message list> file - append messages to file
u <message list> - undelete messages
R <message list> - reply to message senders
r <message list> - reply to message senders and all recipients
pre <message list> -make messages go back to /usr/spool/mail
17 September 2010
TCS Internal
11
The mail - Internal Commands
m <user list> - mail to specific users
q - quit, saving unresolved messages in mbox
x - quit, do not remove system mailbox
h - print out active message headers
! - shell escape
cd [directory] - chdir to directory or home if none given
A <message list> consists of integers, ranges of same, or user names separated by
spaces. If omitted, Mail uses the last message typed.
A <user list> consists of user names or aliases separated by spaces.
File .mailrc in your home directory is invoked when the mail command is executed.
Aliases are defined in this file.
17 September 2010
TCS Internal
12
The finger Command
This product from Berkeley, is more versatile compared to who, and produces an
extremely readable output. finger, when used without arguments - $ finger <Enter>
simply produces a list of all users who are currently logged in (default output of 6 fields
with headings).
finger can also be followed by a list of login names. For each name, it will display a
detailed list, whether logged in or not.
$ finger ntpuser1 <Enter>
Login: ntpuser1 Name: (null)
Directory: /home/ntpuser1 Shell: /bin/bash
Never logged in.
No Plan.
finger can be used with either the first or last name provided the entry has been
properly made in /etc/passwd file.
It is often necessary to leave behind your schedule and other important info for other to
see. Since it is not possible to send mail to all users, finger also shows the contents of
two files .plan and .project (only the first time), both in the home directory.
17 September 2010
TCS Internal
13
The ftp Command
File Transfer Protocol (FTP) is a method of transferring files from one computer to
another. FTP provides the capability of transferring files to and from a remote network
site as well as means for sharing public files. The ftp service is the user interface to the
FTP.
Anonymous FTP enables users to access remote sites without having an authorized
user-id and password. Generally the login-id is anonymous and password is guest.
Most current systems require your e-mail address as the password.
The client host with which ftp is to communicate may be specified on the command line:
$ ftp [option] hostname <Enter>
ftp immediately attempts to establish a connection to an FTP server on that host. A
hostname can be either a domain address or an ip address. After this the remote FTP
server awaits your commands.
17 September 2010
TCS Internal
14
The ftp - Internal Commands
? or help [command] - displays a list of ftp commands; if no argument is given,
displays a list of the known commands.
bell - Sounds a bell after each file transfer.
ascii - Sets the file transfer type to network ASCII (default).
binary or bin - Sets the file transfer type to binary mode.
quit or bye - Terminates the FTP session with the remote computer and
then exits.
cd <remote-directory> - Changes the working directory on the remote machine.
cdup - Goes to the parent of the current remote machines
working directory.
dir or ls [remote-directory] - List the contents of the remote-directory.
Note that the ls command in ftp behaves like the ls al in Linux.
mdir [remote-files] - Like dir, except multiple remote files may be specified.
17 September 2010
TCS Internal
15
The ftp - Internal Commands ...
pwd - Displays cur-work-directory name on remote m/c.
delete remote-file - Deletes remote file on remote m/c.
mdelete [remote-files] - Deletes the remote files on remote machine.
rmdir directory-name - Deletes a directory on the remote machine.
lcd [directory] - Changes working directory on local machine.
If no directory is specified, users home directory is used.
open host [port] - Establishes a connection to specified host FTP server on the
optional port number.
close or disconnect - Terminates the FTP session with the remote server.
17 September 2010
TCS Internal
16
The ftp - Internal Commands
get remote-file [local-file]
Retrieves the remote-file and stores it on local m/c with the same or different name.
mget remote-files
Expands the remote files on the remote m/c and does a getfiles based on regular expressions. For example, f*.tar will get all the files starting
with f.
put local-file [remote-file] - Stores a local file on the remote m/c.
mput local-files - Stores the local files (specified as a regular expression) on the remote m/c with the same names.
However, it is a good practice to set the directories on the local machine and the FTP server before initiating the file transfer.
The I option turns off interactive prompting during multiple file transfers.
Usually <Ctrl-C> is used to abort a sending file transfer. Receiving transfers are halted by sending an ftp ABOR command to the remote
server.
17 September 2010
TCS Internal
17
The telnet Command
It is used to communicate with another host using the TELNET protocol. If telnet is invoked without the host argument, it
enters command mode. Normally you would use-
telnet hostname [port]
where hostname is the host you want to connect to and port indicates a port number (an applications address), else the
default telnet port is used.
telnet can log you in either one of two modes: char-by-char or line-by-line. In char-by-char mode, most text typed is
immediately sent to the remote host for processing. In line-by-line mode, all text is echoed locally, and only completed
lines are sent to the remote host.
17 September 2010
TCS Internal
18
The telnet Command ...
The following commands are available under the command mode:
open host [ [-l] user ] [-port]
Opens a connection to the named host; uses the default port if port number not specified. The [-l] option may be
used to specify the user name.
close Closes a telnet session and returns to cmd-mode
quit Closes any open telnet session and exits telnet. An end of file (in cmd-mode) will also close a session and exit.
? Displays a list of telnet commands.
? [command]
Displays a short summary of the specified command.
set <escape_value> Specifies the character for switching into telnet command mode.
status displays the current status of telnet, including the name of the remote computer the user is connected to.
17 September 2010
TCS Internal
19
Shell Programming and Shell Scripts
17 September 2010
TCS Internal
20
Shell Programming and Shell Scripts
UNIX shell can be considered as a master utility program that enables a user to gain access to all other utilities and
resources of the computer.
Frequently used UNIX commands can be stored in a file. Shell can read the file and execute the commands in it. Such a
file is called a script file.
The script file can be created by:
$ vi filename or
$ cat > filename <Enter>
Executing a Shell Script:
$ sh filename <Enter> or $ filename <Enter>
But, remember to modify the FAP for the file containing the shell script for execute permission: $ chmod u+x filename
<Enter>
Pressing <Ctrl>u at any point, right up to before pressing <Enter>, lets you clear everything on the command line.
17 September 2010
TCS Internal
21
Shell Programming - Variables
User-defined shell variables can be created at any point of time by a simple assignment of a value:
$ today=20 ; var=beta
$ name1=Bharat Bhushan or Bharat Bhushan
NOTE: The assignment operator = must not have surrounding spaces.
Variables can be referenced as:
$ name2=$name1 or name2=${name1} <Enter>
But see what happens when braces are not used:
X=$todayth # would not produce desired result
X=${today}th # would produce 20th
So, braces are optional if no concatenation is involved.
The echo command is used for displaying messages on screen (possibly terminated by \c, \n, \007, etc).
17 September 2010
TCS Internal
22
The Evaluation of Shell Variables
$var value of var; nothing if var undefined
${var} same; useful if alphanumerics follow
variable name
${var-str} value of var if defined; else
str; $var unchanged.
${var=str} value of var if defined; else
str; if undefined, $var set to str.
${var?str} if defined, $var; else, print
str and exit shell; if str empty, print:
var:parameter not set
${var+str} str if $var defined, else null.
17 September 2010
TCS Internal
23
The Global and Local Variables
When a variable is referenced, it is known only to the shell which created it. A new shell created by typing sh, is born unaware of the parent shells
variables.
The same variable name (as in the parent shell) can be given a different value in the new shell. Such a variable is called a local variable that is
known only to the child shell.
In many instances, it may be necessary for the child shell to know about the parent shells variables. They are known as global variables.
$ city=Bombay ; echo $city # Create variable; Response: Bombay
$ sh ; echo $city # create a child shell; No response
$ city=Delhi; echo $city # Create new variable; Response: Delhi
<Press ^d> # Return to parent
echo $city # Parent continues to have value Bombay
The global variables must be exported so that the child shell is aware of them as follows:
$ export city # only the copy passed to the child
17 September 2010
TCS Internal
24
Backward quotes and set & shift commands
Recall the usage of pipes in joining commands. Other way is through command substitution:
$ echo The date is `date` <Enter>
$ count=`cat fileA | wc -l` <Enter>
Single backward quotes enclose command(s) to be executed.
The set command sets the values of $1 to $n to the words given explicitly/implicitly as its arguments:
$ date <Enter>
Fri Sep 24 11:27:42 IST 2004
$ set `date` <Enter>
$ echo $1 $2 $3 <Enter>
Fri Sep 24
The shift command transfers the contents of a positional parameter to a lower numbered one as shown below:
$ shift 2 # Output: 24 11:27:42 IST
Note: shift and shift 1 have the same effect.
17 September 2010
TCS Internal
25
Arithmetic Evaluation with expr
Shell does not support numerical variables. All variables are treated as character strings. Simulation of numeric
variables is possible by expr command which is used to evaluate arithmetic expressions without decimals.
Computing square of n:
n=3
echo Square of $n is `expr ${n} \* ${n}`
n=`expr ${n} + 1` ; echo $n
NOTE
The arithmetic operators (+, -, *, /)must be surrounded by at least one space. The * should be preceded by a
backslash (\) else shell will interpret it as a wildcard character.
Unix understands only the whole numbers, so, 5.2 and 5.6 both are interpreted as 5.
17 September 2010
TCS Internal
26
String Handling with expr
The expr is quite handy for finding the length of a string and extracting a sub-string:
$ str=abcdefghijk ; n=`expr "$str" : .*` ; echo $n
11 # expr gave how many times any character (.*) occurs.
# This feature is very useful in validating data entry.
Extracting a sub-string:
$ expr $str : \(..\)
gh
Note that there are 6 dots preceding the sequence \(..\). This advanced regular expression signifies that the first six
characters of the string are to be ignored and extraction should start from the 7
th
character. Two dots inside \(..\)
suggests that this extraction is limited to two characters only (backslashes override the usual interpretation of ()).
Location of the first occurrence of a character inside string:
$ expr "$str" : '[^d]*d
4
17 September 2010
TCS Internal
27
Shells Built-in Variables and eval command
Shells Built-in Variables
$# The number of arguments
$* all arguments to shell
$@ similar to $*
$- options supplied to the shell
$? Return value of the last command executed
$$ process-id of the shell
$! process-id of the last command started with &
The eval command is used to execute commands generated by multiple levels of indirection:
$ a=c; b=m; c=d; cmd=date
$ eval $`echo $a$b$c`
Tue Nov 23 16:45:43 EDT 2000
17 September 2010
TCS Internal
28
Shell Programming input/output
The read command can be used to get run-time input from the user (standard input). It reads :
$ read var1 var2 <Enter>
A file can also be read sequentially through read:
$ read var1 var2 var3 < myfile
One line is read at a time; the next word in the line is assigned to each successive variable specified as an argument
of read; extra words are assigned to the final argument of read.
Screen display from echo can be redirected (>) or appended (>>) to a file. The double-quoted string formed by
concatenating the fields together separated by the desired delimiter forms echos argument for standard or file
output:
$ echo $name | $code | $price | $qty >> Salesfile
17 September 2010
TCS Internal
29
Coding Branching/Looping Conditions
The test command can be used to write conditions that can be used in if, case, and while commands.
String comparison operators: = != < <= > >=
Example: To check if variables name and myname have the same value, and variable uids value is 10:
test ${name} = ${myname} -a ${uid} = 10
Same as [ ${name} = ${myname} -a ${uid} = 10 ]
Arithmetic comparison operators:
-eq -ne -gt -ge -lt -le
NOTE:
1. All comparison operators must be surrounded by at least one space.
2. Multiple conditions in one test command can be formed using a / -o for Anding / Oring two truth values.
17 September 2010
TCS Internal
30
Options for Testing File-types and Strings
File test options:
Condition Return value when
test -f fname returns true if file exists and is ordinary
test -d fname returns true if file exists and is a directory
test -r fname returns true if file exists and is readable
test -w fname returns true if file exists and is writeable
test -x fname returns true if file exists and is executable
test -s fname returns true if file exists and is not empty
String test options:
test str Returns true if str is not null
test n str Returns true if length of str is greater than zero
test z str Returns true if length of str is equal to zero
The &&, ||, :, ; meta-characters of shell
C1 && C2 Cmd C1 Executed; if success, then C2 Executed.
C1 || C2 Cmd C1 Executed; if failure, then C2 Executed.
: - Do-nothing command - used mostly in shell scripts.
; - Command separator used to type multiple cmds in a line.
17 September 2010
TCS Internal
31
Decision-making Constructs
1. if <condition(s)>
then <command(s)>
[else <command(s)>] # Optional else part
fi
2. if <condition(s)>
then <command(s)>
elif <condition(s)> # Many elif-then allowed
then <command(s)>
else <command(s)>
fi
Example:
echo Want to quit (type Y or y):
read ans
if test $ans = y o $ans = Y
then exit
fi
17 September 2010
TCS Internal
32
Decision-making Constructs ...
3. case-esac command in shell scripts is a multiple-choice construct:
case ${num} in
dozen) echo 12;;
score) echo 20;;
*) echo num is neither a dozen nor a score
esac
NOTE: the last command in any choice must be delimited by a pair of semi-colons to delimit it from the commands
of the next choice.
4. exit command is used to exit from the shell script and return to the parent shell. It also takes an argument whose
value is 0 when not specified. It is taken as the return value which is assigned to the parameter $?.
17 September 2010
TCS Internal
33
Constructs for Supporting Iteration
1. while <condition>
do # executed as long as the condition is true
<command(s)>
done
2. until <condition> # complement of while
do # executed as long as the condition is false
<command(s)>
done
n=0
while [ $n -lt 10 ]
do n=`expr $n + 1`
echo $n `expr $n \* $n`
done
Example
17 September 2010
TCS Internal
34
Constructs for Supporting Iteration
3(a) for n in 1 7 8 50
do
echo Value of n is $n
done
3(b) for filename in `ls tempdir`
do
echo Displaying contents of ${filename}
cat ${filename}
done
3(c) for itemlist; do commands; done
# executes once for each item in itemlist that contains all positional
# parameters passed in to shell program on the command line.
For each iteration in both loops, variable n and filename take on one value from their lists.
Command break causes the termination of a loop and continue resumes execution at its top.
17 September 2010
TCS Internal
35
Shell Scripts with Command-line Parameters
Parameters are essentially used to create generalized shell scripts. The command name (first word on command line)
is put into a variable called $0, the first argument of command (second word) is put into $1, etc.
UNIX shell creates a maximum of ten variables. The variables $1 through $9 are also called the positional parameters
of the command line.
A Shell Script test with Parameters:
echo Program name is $0
echo First argument is $1
echo Number of arguments = $#
echo The arguments are $*
A Sample Run:
$ sh test arg1 arg2 arg3 <Enter>
Program name is test
First argument is arg1
Number of arguments = 3
The arguments are arg1 arg2 arg3
17 September 2010
TCS Internal
36
Process
17 September 2010
TCS Internal
37
Background Processing
UNIX provides a method of running time-consuming commands in the background while the user continues working
in the foreground by typing ampersand (&) at the end of line:
$ wc myfile & <Enter>
$ vi newfile <Enter>
Here, user gives the wc command and then immediately begins editing newfile without waiting for the completion of
the previous wc process.
Well, the user must be careful that the background and foreground processes do not interfere with each other. Any
screen output from the background process would disrupt the screen in the middle of users work with the foreground
process. This should be avoided by output redirection:
$ wc myfile 1 > outfile 2 > errfile & <Enter>
$ vi newfile <Enter>
17 September 2010
TCS Internal
38
Background Processing
Sometimes it is needed to check the current status of a background process. The jobs command gives the job-number of
each active process. The ps command generates a one-line entry for each of the active processes showing its process-id,
users terminal number, time for which the process has been active, and the name of command. If the background
process is not listed in the output, it may be completed already. The kill command can be used to stop background
process if it is not functioning as desired:
$ kill process-id <Enter> or, $ kill job-number <Enter>
If a command issued in foreground is taking too long to finish, and you want to execute it in background so that you could
use the system again, do the following:
$ <Ctrl> z bg
Pressing <Ctrl>z suspends a running process and bg restarts it in background. <Ctrl> c kills a job running in foreground.
Similarly, <Ctrl>z fg pid or <Ctrl>z fg %jobnumber forces a suspended process to continue to execute in the foreground.
17 September 2010
TCS Internal
39
UNIX SYSTEM CALLS
17 September 2010
TCS Internal
40
UNIX SYSTEM CALLS
system call is the mechanism used by an application
program to request service from the operating system, or
more specifically, the operating system kernel.
Different privilege levels are provided so that operating
systems can restrict the operations that programs running
under them can perform, for reasons of security and
stability.
Such operations include accessing hardware devices,
enabling and disabling interrupts, and accessing memory
management units. The operating system kernel would run
in supervisor mode, and user applications in user mode.
17 September 2010
TCS Internal
41
i~==~==~
_=~=`=J =
a=======~====rkfu=p
i~=====~====~===~J=
p=~=~=~===rkfu=h
p=`~=~==~=rkfu==
i~=======~=~=~===
~===
17 September 2010
TCS Internal
42
File Related Operations
1. opening files
2. reading files
3. writing in files
4. creating files
5. changing the permission of files
6. changing the owner and group of files
7. seeking to file-location
8. closing files
17 September 2010
TCS Internal
43
1. opening files open()
2. reading files read()
3. writing in files write()
4. creating files creat()
5. changing the permission of files chmod()
6. changing the owner and group of files chown()
7. seeking to file-location lseek()
8. closing files close()
Related System calls
17 September 2010
TCS Internal
44
open()
The open system call can be used to open an
existing file or to create a new file if it does not exist already.
# include <sys/types.h>
# include <sys/stat.h>
# include <fnctl.h>
int open(const char *path, int flags);
int open(const char *path, int flags, int modes);
The first form is normally used to open an existing file,
The second form to open a file and to create a file
if it does not exist already.
Both forms returns an integer called the file descriptor.
The file descriptor will be used for reading from and writing
to the file.
If the file cannot be opened or created, it returns -1.
17 September 2010
TCS Internal
45
The first parameter path in both forms specifies the file name to be
opened or created.
The second parameter (flags) specifies how the file may be used.
The following list some commonly used flag values.
Flag Description
O_RDONLY open for reading only
O_WRONLY open for writing only
O_RDWR open for reading and writing
O_APPEND append on each write
O_CREAT create file if it does not exist
Continued... open()
17 September 2010
TCS Internal
46
Constant Name
Octal
Value
Description
S_IRWXU 0000700 rwx mask for owner
S_IRUSR 0000400 r for owner
S_IWUSR 0000200 w for owner
S_IXUSR 0000100 x for owner
S_IRWXO 0000007 rwx mask for other
S_IROTH 0000004 r for other
S_IWOTH 0000002 w for other
S_IXOTH 0000001 x for other
R: read, W: write, and X:
executable
Commonly used modes (or access permissions) include
Continued... open()
17 September 2010
TCS Internal
47
For example, to open file "tmp.txt" in the current working directory
for reading and writing:
fd = open("tmp.txt", O_RDWR);
To open tmp.txt" in the current working directory
for appending or create it, if it does not exist, with read,
write and execute permissions for owner only:
fd = open("tmp.txt", O_WRONLY|O_APPEND|O_CREAT, S_IRWXU);
A file may be opened or created outside the current working
directory.
In this case, an absolute path and relative path may prefix the file
name.
For example, to create a file in /tmp directory:
open("/tmp/tmp.txt", O_RDWR);
Continued... open()
17 September 2010
TCS Internal
48
Example :
Opening the file test in read mode and checking for
the error condition
int fd;
fd = open(/usr/trg/test, O_RDONLY );
if ( fd == -1 )
{
printf(error in opening file test);
exit(1);
}
Continued... open()
17 September 2010
TCS Internal
49
creat()
int creat (char * pathname, int fileMode);
The named file is created as an empty file and opened for writing, and a
positive integer, the open file descriptor is returned.
The file location is set to 0. The
fileMode (in decimal) defines file access rights.
If an error occurs in trying to create the file, a negative integer is returned.
The open file descriptor returned by open and creat are local to the
process making the calls. Thus, an open file descriptor in one process is
not related to an open file identifier in another process.
# include <sys/types.h>
# include <sys/stat.h>
# include <fnctl.h>
17 September 2010
TCS Internal
50
create system call creates and opens a file for writing.
if the file does not exists, creates a file with mode
permissions.
If file does exists the contents are discarded
and the mode value is ignored.
The perminssions of the existing file is retained
Continued... creat()
17 September 2010
TCS Internal
51
The close system call closes a file. Its syntax is
# include <unistd.h>
int close(int fd);
It returns the value 0 if successful;
otherwise the value -1 is returned
close()
17 September 2010
TCS Internal
52
The system call for reading from a file is read.
# include <unistd.h>
int read(int fd, char *buf, size_t nbytes);
The first parameter fd is the file descriptor of the file you want
to read from, it is normally returned from open.
The second parameter buf is a pointer pointing the memory
location where the input data should be stored.
The last parameter nbytes specifies the maximum number of
bytes you want to read.
The system call returns the number of bytes it actually read,
and normally this number is either smaller or equal to nbytes.
read()
17 September 2010
TCS Internal
53
Each file has a pointer, normally called read/write offset,
indicating where next read will start from.
This pointer is incremented by the number of bytes actually read by the
read call.
For the above example, if the offset was zero before the read and it
actually read 1024 bytes, the offset will be 1024 when the read returns.
This offset may be changed by the system call lseek, which will be
covered shortly.
int actual_count = 0;
int fd = open("tmp.txt", O_RDONLY);
char *buf = (char*) malloc(1024);
actual_count = read(fd, buf, 1024);
The following segment of code reads up to 1024 bytes from file
tmp.txt:
Continued... read()
17 September 2010
TCS Internal
54
Example :
Reading the file test 100 characters at a time
while ( ( n = read(fd,buff,100)) > 0 )
{
printf(file test has contents %s ,buff);
}
if ( n == 0 )
printf ( End of file );
if ( n == -1 )
printf (Error in reading file test);
When each read is finished the pointer advances by 100 bytes so that
the next read picks from there
If the number of characters left are less than nbytes ( in this example -
100 ) then read() will pick up what is left over
Continued... read()
17 September 2010
TCS Internal
55
The system call write is to write data to a file.
# include <unistd.h>
ssize_t write(int fd, const void *buf, size_t nbytes);
It writes nbytes of data to the file referenced by file descriptor fd
from the buffer pointed by buf.
The write starts at the position pointed by the offset of the file.
Upon returning from write, the offset is advanced by the
number of bytes which were successfully written.
The function returns the number of bytes that were actually
written, or it returns the value -1 if failed.
write()
17 September 2010
TCS Internal
56
b~=W
whlle ( ( n teoJ (lJ,oull,100}} > 0 }
(
n1 wtlte (1,oull,100},
/ wtltln to stonJotJ outut /
/ llle lJ :-> 1 ls lot stJout /
ll ( n1 -1 }
tlntl (lttot ln wtltln on stJout"},
}
ll ( n -1 }
tlntl (lttot ln teoJln llle test "},
Continued... write()
17 September 2010
TCS Internal
57
The lseek system call allows random access
to a file by reposition the offset for next read or write.
# include <unistd.h>
# include <sys/types.h>
long lseek(int fd, long offset, int reference);
It repositions the offset of the file descriptor fd to the
argument offset according to the directive reference.
The reference indicate whether offset should be considered
from the beginning of the file (with reference 0),
from the current position of the read/write offset (with
reference 1),
or from the end of the file (with reference 2).
The call returns the byte offset where the next read/write
will start.
lseek()
17 September 2010
TCS Internal
58
b~=W
tet lseel(lJ,1000,0},
ll ( tet -1 }
(
tlntl(ettot ln seelln to the 1000th oyte ol the llle },
}
EINMMMIMF=======NMMM=======~ ~==
~===NMMN=
17 September 2010
TCS Internal
59
The unlink may be used to delete a file (A file may have multiple
names (also called links), here we assume that a file in this
context has only one name or link.).
# include <unistd.h>
int unlink(const char *path);
path is the file name to be deleted.
The unlink system call returns the value 0 if successful, otherwise
it returns the value -1.
unlink()
17 September 2010
TCS Internal
60
File access permissions may be set using the chmod system call
(note that there is a command with the same name for setting
access permissions.). It has two forms:
# include <sys/types.h>
# include <sys/stat.h>
int chmod(const char *path, int mode); or
int fchmod(int fd, int mode);
Both forms set the access permission of a file to mode.
In the first form the file is identified by its name, and in the second
it is identified by a file descriptor returned from the open system
call.
The system call returns the value 0 if successful, otherwise it
returns the value -1.
chmod()
17 September 2010
TCS Internal
61
b~=W
tet chmoJ(test.c,0600},
ll ( tet -1 }
(
tlntl(ettot ln chonln the llle etmlsslon},
}
`~=====K
KKI==~=~=====
Continued... chmod()
17 September 2010
TCS Internal
62
To change the owner and group of a file
# include <unistd.h>
# include <sys/unistd.h>
int chown(const char * filename, int owner, int group);
Where the the filename names the file and owner and group are the
new owner and group id for the file.
If the owner or group is specified as 1, then that id is not changed.
Only the super-user can change the owner of the file.
The owner of the file may change the group of the file to any group
of which that owner is a member.
chown()
17 September 2010
TCS Internal
63
Process Related System calls
17 September 2010
TCS Internal
64
G===EF=~=~=======~==
G===`====~=~======~=
G===m~==~=======
`==~==M
# lnlcuJe <sys/tyes.h>
#lncluJe<unlstJ.h>
lnt lotl(volJ}
fork ()
17 September 2010
TCS Internal
65
if (!fork())
{
printf("I'm the child!\n");
exit(0);
}
else
{
printf("I'm the parent!\n");
wait(NULL);
}
Continued... fork()
17 September 2010
TCS Internal
66
G==EF==========~==============
G==EF===~=====~=

getpid () getppid ()
17 September 2010
TCS Internal
67
#lncluJe <stJlo.h>
moln(}
(
lnt lJ ,
lnt lJ , t ,
lnt lJ ,
lJ lotl(},
tlntl (PPl0 - J Pl0- J lJ - J \n, etlJ(} ,
etlJ(} ,lJ },
tlntl (PCkP - J \n , ett(} },
}
Continued...
17 September 2010
TCS Internal
68
wait() causes a parent to stop running and await the
termination of a child process
wait()
#include sys/types.h>
#include<sys/wait.h>
int wait(int * status)
wait() returns the pid of the process that ended.
status stores the value returned by the child process
17 September 2010
TCS Internal
69
exec
The exec system calls reinitialize a process from a
designated program; the program changes while the process
remains
On the other hand, the fork system call creates a new
process that is a clone of an existing one, by just copying
over the instruction, user-data and system-data segments;
the new process is not initialized from a program, so old and
new processes execute
the same instructions.
17 September 2010
TCS Internal
70
Actually, there is no system call named exec. The so-called
exec system calls are a set of six, with names of the form
execAB, where A is either l or v, depending on whether the
arguments are directly in the call (list) or in an array (vector),
and B is either absent, a p to indicate that the PATH
environment variable should be used to search for the
program, or an e to indicate that a particular environment is
to be used. (Oddly, you cant get both the p and e features
in the same call.) Thus, the six names are
execl, execv, execlp, execvp, execle, and execve.
Continued... exec
17 September 2010
TCS Internal
71
#include <unistd.h>
int execl(
const char *path, /* program pathname */
const char *arg0, /* first arg (file name) */
const char *arg1, /* second arg (if needed) */
..., /* remaining args (if needed) */
NULL /* arg list terminator */
);
Continued... exec
17 September 2010
TCS Internal
72
The argument path must name a program file that is
executable by the effective user-ID (mode 755, say)
and has the correct contents for executable programs.
The processs instruction segment is overwritten by the
instructions from the program, and the processs user-
data segment is overwritten by the data from the
program, with a re-initialized stack. Then the process
executes the new program from the top (that is, its
main function is called).
Continued... exec
17 September 2010
TCS Internal
73
There can be no return from a successful execl
because the return location is gone. An unsuccessful
execl does return, with a value of 1,
The arguments to execl that follow path are collected
into an array of character pointers; the last argument,
which must be NULL, stops the collection and terminates
the array.
The first argument, by convention, is the name of the
program file (not the entire path).
The environment pointed to by environ is passed on,
too, and it is accessible through the new programs
environ pointer or with getenv
Continued... exec
17 September 2010
TCS Internal
74
b~===EF
#lncluJe <stJlo.h>
moln(}
(
lnt lJ,
tlntl ( Potent tocess \n},
ll ( ( lJ lotl(} } 0 }
(
tlntl(5totement ltom chllJ tocess\n},
execl(/oln/Jote,Jote,0},
}
tlntl( Potent tocess ooln \n},
}
Continued... exec
17 September 2010
TCS Internal
75
execvexecute file with argument vector
#include <unistd.h>
int execv(
const char *path, /* program pathname */
char *const argv[] /* argument vector */
);
/* Returns -1 on error (sets errno) */
Continued...
17 September 2010
TCS Internal
76
execlpexecute file with argument list and PATH search
#include <unistd.h>
int execlp(
const char *file, /* program file name */
const char *arg0, /* first arg (file name)
*/
const char *arg1, /* second arg (if needed)
*/
..., /* remaining args (if needed) */
NULL /* arg list terminator */
);
/* Returns -1 on error (sets errno) */
Continued... exec
17 September 2010
TCS Internal
77
execvpexecute file with argument vector and PATH
search
#include <unistd.h>
int execvp(
const char *file, /* program file name */
char *const argv[] /* argument vector */
);
/* Returns -1 on error (sets errno) */
Continued... exec
17 September 2010
TCS Internal
78
execleexecute file with argument list and environment
#include <unistd.h>
int execle(
const char *path, /* program pathname */
const char *arg0, /* first arg (file name)
*/
const char *arg1, /* second arg (if
needed) */
..., /* remaining args (if needed) */
NULL, /* arg list terminator */
char *const envv[] /* environment vector
*/
);
Continued... exec
17 September 2010
TCS Internal
79
execveexecute file with argument vector and
environment
#include <unistd.h>
int execve(
const char *path, /* program pathname */
char *const argv[], /* argument vector */
char *const envv[] /* environment vector
*/
);
/* Returns -1 on error (sets errno) */
Continued... exec
17 September 2010
TCS Internal
80
Inter Process Communication
17 September 2010
TCS Internal
81
Signals are software generated interrupts that are sent to a process when a
event happens.
Signals can be synchronously generated by an error in an application, such as
SIGFPE and SIGSEGV, but most signals are asynchronous.
Signals can be posted to a process when the system detects a software event,
such as a user entering an interrupt or stop or a kill request from another
process.
Signals can also be come directly from the OS kernel when a hardware event
such as a bus error or an illegal instruction is encountered.
Signals
17 September 2010
TCS Internal
82
Some signals stop the receiving process and other signals can be
ignored. Each signal has a default action which is one of the
following:
The signal is discarded after being received
The process is terminated after the signal is received
A core file is written, then the process is terminated
Stop the process after the signal is received
Each signal defined by the system falls into one of five classes:
Hardware conditions
Software conditions
Input/output notification
Process control
Resource control
Continued... Signals
17 September 2010
TCS Internal
83
Macros are defined in <signal.h> header file for common
signals.
These include:
SIGHUP 1 /* hangup */
SIGINT 2 /* interrupt */
SIGQUIT 3 /* quit */
SIGILL 4 /* illegal instruction */
SIGABRT 6 /* used by abort */
SIGKILL 9 /* hard kill */
SIGALRM 14 /* alarm clock */
SIGCONT 19 /* continue a stopped process */
SIGCHLD 20 /* to parent on child stop or exit */
Signals can be numbered from 0 to 31.
Continued... Signals
17 September 2010
TCS Internal
84
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
int main(void)
{
void sigint_handler(int sig); /* prototype */
char s[200];
/* set up the handler */
if (signal(SIGINT, sigint_handler) == SIG_ERR) {
perror("signal");
exit(1);
}
Continued... Signals
17 September 2010
TCS Internal
85
printf("Enter a string:\n");
if (gets(s) == NULL)
perror("gets");
else
printf("You entered: \"%s\"\n", s);
return 0;
}
/* this is the handler */
void sigint_handler(int sig)
{
printf("Not this time!\n");
}
Continued... Signals
17 September 2010
TCS Internal
86
A FIFO ("First In, First Out", pronounced "Fy-Foh") is sometimes known as
a named pipe. That is, it's like a pipe, except that it has a name! In this
case, the name is that of a file that multiple processes can open() and read
and write to.
Named pipes exist as a device special file in the file system.
Processes of different ancestry can share data through a named pipe.
When all I/O is done by sharing processes, the named pipe remains in the
file system for later use.
Named Pipes
17 September 2010
TCS Internal
87
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <linux/stat.h>
#define FIFO_FILE "MYFIFO"
int main(void)
{
FILE *fp;
char readbuf[80]; /* Create the FIFO if it does not exist */
umask(0);
mknod(FIFO_FILE, S_IFIFO|0666, 0);
while(1)
{
fp = fopen(FIFO_FILE, "r"); fgets(readbuf, 80, fp);
printf("Received string: %s\n", readbuf);
fclose(fp);
}
return(0);
}
Continued... Pipes
17 September 2010
TCS Internal
88
#include <stdio.h>
#include <stdlib.h>
#define FIFO_FILE "MYFIFO"
int main(int argc, char *argv[])
{
FILE *fp;
if ( argc != 2 )
{
printf("USAGE: fifoclient [string]\n");
exit(1);
}
if((fp = fopen(FIFO_FILE, "w")) == NULL)
{
perror("fopen");
exit(1);
}
fputs(argv[1], fp);
fclose(fp);
return(0);
}
Continued... Pipes
17 September 2010
TCS Internal
89
make
17 September 2010
TCS Internal
90
The make utility automatically determines which pieces of a
large program need to be recompiled, and issues commands
to recompile them
To prepare to use make, you must write a file called the
makefile that describes the relationships among files in your
program and provides commands for updating each file.
In a program, typically, the executable file is updated from
object files, which are in turn made by compiling source files.
make
17 September 2010
TCS Internal
91
Once a suitable makefile exists, each time you change
some source files, this simple shell command:
make
suffices to perform all necessary recompilations. The
make program uses the makefile data base and the
last-modification times of the files to decide which of
the files need to be updated.
For each of those files, it issues the commands
recorded in the data base.
make
17 September 2010
TCS Internal
92
Here is a makefile that describes the way an executable file
called edit depends on eight object files which, in turn,
depend on eight C source and three header files.
In this example, all the C files include defs.h, but only those
defining editing commands include command.h, and only low
level files that change the editor buffer include buffer.h.
make
17 September 2010
TCS Internal
93
edit : main.o kbd.o command.o display.o \
insert.o search.o files.o utils.o
cc -o edit main.o kbd.o command.o display.o \
insert.o search.o files.o utils.o
main.o : main.c defs.h
cc -c main.c
kbd.o : kbd.c defs.h command.h
cc -c kbd.c
command.o : command.c defs.h command.h
cc -c command.c
display.o : display.c defs.h buffer.h
cc -c display.c
insert.o : insert.c defs.h buffer.h
cc -c insert.c
search.o : search.c defs.h buffer.h
cc -c search.c
files.o : files.c defs.h buffer.h command.h
cc -c files.c
utils.o : utils.c defs.h
cc -c utils.c
clean :
rm edit main.o kbd.o command.o display.o insert.o search.o files.o utils.o
make
17 September 2010
TCS Internal
94
To use this makefile to create the executable file called
edit, type:
make
To use this makefile to delete the executable file and all
the object files from the directory, type:
make clean
In the example makefile, the targets include the
executable file `edit', and the object files `main.o' and
`kbd.o'. The prerequisites are files such as `main.c' and
`defs.h'. In fact, each `.o' file is both a target and a
prerequisite. Commands include `cc -c main.c' and `cc -
c kbd.c'
make
17 September 2010
TCS Internal
95
The target `clean' is not a file, but merely the name of an
action. Since you normally do not want to carry out the
actions in this rule, `clean' is not a prerequisite of any other
rule.
when you give the command: make
make reads the makefile in the current directory and begins
by processing the first rule. In the example, this rule is for
relinking edit; but before make can fully process this rule, it
must process the rules for the files that edit depends on,
which in this case are the object files. Each of these files is
processed according to its own rule. These rules say to
update each `.o' file by compiling its source file. The
recompilation must be done if the source file, or any of the
header files named as prerequisites, is more recent than the
object file, or if the object file does not exist
make
17 September 2010
TCS Internal
96
The other rules are processed because their targets appear as
prerequisites of the goal. If some other rule is not depended on
by the goal (or anything it depends on, etc.), that rule is not
processed, unless you tell make to do so (with a command such
as make clean).
Before recompiling an object file, make considers updating
its prerequisites, the source file and header files. This makefile
does not specify anything to be done for themthe `.c' and `.h' files
are not the targets of any rulesso make does nothing for these files.
make
17 September 2010
TCS Internal
97
objects = main.o kbd.o command.o display.o \
insert.o search.o files.o utils.o
edit : $(objects)
cc -o edit $(objects)
main.o : main.c defs.h
cc -c main.c
kbd.o : kbd.c defs.h command.h
cc -c kbd.c
command.o : command.c defs.h command.h
cc -c command.c
display.o : display.c defs.h buffer.h
cc -c display.c
insert.o : insert.c defs.h buffer.h
cc -c insert.c
search.o : search.c defs.h buffer.h
cc -c search.c
files.o : files.c defs.h buffer.h command.h
cc -c files.c
utils.o : utils.c defs.h
cc -c utils.c
clean :
rm edit $(objects)
make
define a variable objects with a line like this in the makefile:
objects = main.o kbd.o command.o display.o insert.o search.o files.o utils.o
Then, each place we want to put a list of the object file names,we can substitute the variable's
value by writing `$(objects)'
17 September 2010
TCS Internal
98
objects = main.o kbd.o command.o display.o \
insert.o search.o files.o utils.o
edit : $(objects)
cc -o edit $(objects)
main.o : defs.h
kbd.o : defs.h command.h
command.o : defs.h command.h
display.o : defs.h buffer.h
insert.o : defs.h buffer.h
search.o : defs.h buffer.h
files.o : defs.h buffer.h command.h
utils.o : defs.h
clean : rm edit $(objects)
make
It is not necessary to spell out the commands for compiling the individual C
source files, because make can figure them out: it has an implicit rule for
updating a `.o' file from a correspondingly named `.c' file using a `cc -c'
command. When a `.c' file is used automatically in this way, it is also
automatically added to the list of prerequisites. We can therefore omit
the `.c' files from the prerequisites, provided we omit the commands.

Você também pode gostar