Docsity

Systems Programming - Lecture Notes | CSC 3320, Study notes of Computer Science

Toggle sidebar
bg1
1
Chapter 13
Systems Programming
Graham Glass and King Ables,
UNIX for Programmers and Users,
Third Edition Pearson Prentice Hall 2003
2008-12-1 cs3320 1
Third
Edition
,
Pearson
Prentice
Hall
,
2003
.
Original Notes by Raj Sunderraman
Converted to presentation and updated by
Michael Weeks
Systems Programming
• UNIX System calls: C functions that provide
access to the file system, processes, and error
handling.
•S
y
stem Calls
g
rou
p
ed into 3 main cate
g
ories:
2008-12-1 cs3320 2
ygp g
– File Management (Fig. 13.1)
– Process Management (Fig. 13.2)
– Error Handling (Fig. 13.3)
Error Handling
• Most system calls are capable of failing in some
way.
• Example: open a file may fail because file does
not exist!
2008-12-1 cs3320 3
• System call returns a value of -1 when it fails.
• This value does not tell much about the cause of
the failure.
Error Handling
• global variable errno
– holds the numeric code of the last system-call error
• function perror() describes the system-call error
•
void perror(char
*
str)
2008-12-1 cs3320 4
void
perror(char
str)
– /* standard C function in stdio.h */
– Displays str followed by : followed by a description of
the last system call error.
– Error 0 is displayed if no error
– See example showErrno.c
Example: File I/O
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
main () {
int fd;
/* Open a non-existent file to cause an error */
fd = open ("nonexist.txt", O_RDONLY);
if (fd == -1) /* fd == -1 =, an error occurred */ {
2008-12-1 cs3320 5
printf ("errno = %d\n", errno);
perror ("main");
}
/* Force a different error */
fd = open ("/", O_WRONLY);
if (fd == -1) {
printf ("errno = %d\n", errno);
perror ("main");
}
Example: File I/O
/* Execute a successful system call */
fd = open ("nonexist.txt", O_RDONLY | O_CREAT, 0644);
/* Display after successful call */
printf ("errno = %d\n", errno);
/* ill di l i (21) */
2008-12-1 cs3320 6
/*
w
ill
di
sp
l
ay prev
i
ous error num
(21)
*/
perror ("main");
errno = 0; /* Manually reset error variable */
perror ("main");
}$ showError
errno = 21
main: Is a directory
errno = 29
main: Illegal seek
main: Success
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Systems Programming - Lecture Notes | CSC 3320 and more Study notes Computer Science in PDF only on Docsity!

Chapter 13

Systems Programming

Graham Glass and King Ables,

UNIX for Programmers and Users ,

Third Edition Pearson Prentice Hall 2003

2008-12-1 cs3320 1

Third Edition, Pearson Prentice Hall, 2003.

Original Notes by Raj Sunderraman

Converted to presentation and updated by

Michael Weeks

Systems Programming

• UNIX System calls: C functions that provide

access to the file system, processes, and error

handling.

• System Calls grouped into 3 main categories:

2008-12-1 cs3320 2

y g p g

– File Management (Fig. 13.1)

– Process Management (Fig. 13.2)

– Error Handling (Fig. 13.3)

Error Handling

• Most system calls are capable of failing in some

way.

• Example: open a file may fail because file does

not exist!

2008-12-1 cs3320 3

• System call returns a value of -1 when it fails.

• This value does not tell much about the cause of

the failure.

Error Handling

• global variable errno

– holds the numeric code of the last system-call error

• function perror() describes the system-call error

• void perror(char* str)

2008-12-1 cs3320 4

void perror(char str)

– /* standard C function in stdio.h */

– Displays str followed by : followed by a description of

the last system call error.

– Error 0 is displayed if no error

– See example showErrno.c

Example: File I/O

#include <stdio.h>

#include <fcntl.h>

#include <errno.h>

main () {

int fd;

/* Open a non-existent file to cause an error */

fd = open ("nonexist.txt", O_RDONLY);

if (fd == -1) /* fd == -1 =, an error occurred */ {

printf ("errno = %d\n", errno);

perror ("main");

/* Force a different error */

fd = open ("/", O_WRONLY);

if (fd == -1) {

printf ("errno = %d\n", errno);

perror ("main");

Example: File I/O

/* Execute a successful system call */

fd = open ("nonexist.txt", O_RDONLY | O_CREAT, 0644);

/* Display after successful call */

printf ("errno = %d\n", errno);

/* ill di l i (21) */

/* will display previous error num (21) */

perror ("main");

errno = 0; /* Manually reset error variable */

perror ("main");

} $ showError

errno = 21 main: Is a directory errno = 29 main: Illegal seek main: Success

File Management

• System Calls: open, fcntl, read, write, lseek,

unlink, close

• Typical sequence:

– open

2008-12-1 cs3320 7

p

– Each read() and write() invokes a system call!

– Close

– All data are processed as a series of bytes (no

format)

2008-12-1 cs3320 8

2008-12-1 cs3320 9 2008-12-1 cs3320 10

UNIX File

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

#include <stdio.h>

#include <stdlib.h>

int main()

int fd1, fd2;

What is the output of the following program?

2008-12-1 cs3320 19

fd1 = open("foo1.txt", O_RDONLY, 0);

close(fd1);

fd2 = open("foo2.txt", O_RDONLY, 0);

printf("fd2 = %d\n", fd2);

exit(0);

openopen always returnsalways returns lowestlowest unopened descriptorunopened descriptor

File I/O – creat() and close()

#include <sys/types>

#include <sys/stat.h>

#include <fcntl.h>

int creat(const char*pathname, int mode);

• open(pathname, O_WRONLY | O_CREAT | O_TRUNC, mode)

• This interface is made obsolete by open

• Only for write-access.

2008-12-1 cs3320 20

y

• Q: What if you want to create a file for READ and WRITE?

#include <unistd.h>

int close(int filedes);

• All open files are automatically closed by the kernel when a process

terminates

• Closing a file descriptor releases any record locks on that file

mode Flags for O_CREAT

• Defined in <sys/stat.h>

– S_IRUSR: owner read permit

– S_IWUSR: owner write permit

– S_IXUSR: owner execute permit

– S_IRGRP: group read permit

– S_IWGRP: group write permit

S IROTH th d it

2008-12-1 cs3320 21

– S_IROTH: others read permit

– S_IWOTH: owners write permit

– S_IXOTH: others execute permit

• open(“myfile”, O_CREAT, S_IRUSR | S_IXOTH)

File I/O - lseek

#include <sys/types>

#include <unistd.h>

off_t lseek(int filedes, off_t offset, int whence);

• Current file offset in bytes

• changes file pointer

• whence: SEEK_SET, SEEK_CUR, SEEK_END

  • determines how offset is to be used

2008-12-1 cs3320 22

  • determines how offset is to be used
  • SEEK_SET : offset relative to start of file
  • SEEK_CUR : offset relative to current position of file
  • SEEK_END : offset relative to end of file

• off_t: typedef long off_t; /* 2^31 bytes */

– or typedef longlong_t off_t; /* 2^63 bytes */

• lseek fails if moved before start of file

  • returns new file position if successful
  • returns -1 if unsuccessful

Current Offset of lseek

• To find out current position use:

– currentOffset = lseek(fd, 0, SEEK_CUR);

• If you move past the end of file and write there, Unix

automatically extends the size of the file and treats intermediate

area as NULLS (0)

• Unix does not allocate disk area for intermediate space!!

• (see next example)

  • File size is 50 (bytes) Æ 0000000 a b c d e f g h i j \0 \0 \0 \0 \0
    Æ 0000020 \0………………………………
    Æ 0000040 A B C D E F G H I J \0 ………
    Æ 0000060

2008-12-1 cs3320 25

File I/O – read and write

#include <unistd.h>

ssize_t read(int filedes, void *buf, size_t nbytes);

  • copy upto count bytes from the file referenced by fd into buffer buf
    • returns 0 if it attempts to copy after end of file
    • returns -1 if unsuccessful
  • the bytes are read from current position (file pointer) which is then

updated accordingly

  • Less than nbytes of data are read:

2008-12-1 cs3320 26

  • EOF(0): terminal device (line-input), network buffering, record-oriented devices (e.g., tape)
  • -1: error
  • Offset is increased for every read()

#include <unistd.h>

ssize_t write(int filedes, const void *buf, size_t nbytes);

  • Copy upto count bytes from a buffer buf into the file referenced by fd
  • Write errors for disk-full or file-size-limit causes.
  • When O_APPEND is set, the file offset is set to the end of the file

before each write operation.

Suppose that foobar.txt consists of the 6 ASCII characters

"foobar". Then what is the output of the following program?

int main()

int fd1, fd2;

char c;

fd1 = open("foobar.txt", O_RDONLY, 0);

fd2 = open("foobar txt" O RDONLY 0);

2008-12-1 cs3320 27

fd2 = open( foobar.txt , O_RDONLY, 0);

read(fd1, &c, 1);

read(fd2, &c, 1);

printf("c = %c\n", c);

exit(0);

The descriptors fd1 and fd2 each have their own open file table entry,

so each descriptor has its own file position for foobar.txt. Thus, the

read from fd2 reads the first byte of foobar.txt

The descriptors fd1 and fd2 each have their own open file table entry,

so each descriptor has its own file position for foobar.txt. Thus, the

read from fd2 reads the first byte of foobar.txt

I/O Efficiency

How do you move from home to dorm?

2008-12-1 cs3320 28

Closing a file: close()

• int close(int fd);

• Frees fd; releases resources

• When a process terminates, all fds are automatically closed

• Still it is a good idea to close yourself

• Returns

Returns

– 0 if success

– -1 if failure

Opening a Directory Stream

• Function: DIR * opendir (const char *dirname)

  • The opendir function opens and returns a directory stream for reading the directory whose file name is dirname. The stream has type DIR *.
  • If unsuccessful, opendir returns a null pointer.
  • Data Type: struct dirent
  • This is a structure type used to return information about directory entries.
  • It contains the following fields:g
  • char d_name[] This is the null-terminated file name component.
  • ino_t d_fileno This is the file serial number.
  • unsigned char d_namlen This is the length of the file name, not including the terminating null character. Its type is unsigned char because that is the integer type of the appropriate size
  • unsigned char d_type This is the type of the file, possibly unknown. The following constants are defined for its value:
  • DT_UNKNOWN The type is unknown. On some systems this is the only value returned.
  • DT_REG A regular file.
  • DT_DIR A directory.
  • DT_FIFO A named pipe, or FIFO.
  • DT_SOCK A local-domain socket.
  • DT_CHR A character device.
  • DT_BLK A block device. 2008-12-1 cs3320 37

Reading and Closing a Directory Stream

• Function: struct dirent * readdir (DIR *dirstream)

  • This function reads the next entry from the directory. It normally returns a pointer to a structure containing information about the file. This structure is statically allocated and can be rewritten by a subsequent call.
  • If there are no more entries in the directory or an error is detected, readdir returns a null pointer. The following errno error conditions are defined for this function:function: - EBADF The dirstream argument is not valid.
  • Function: int closedir (DIR *dirstream)
  • This function closes the directory stream dirstream. It returns 0 on

success and -1 on failure.

  • The following errno error conditions are defined for this function:
    • EBADF The dirstream argument is not valid.

2008-12-1 cs3320 38

Sample code

#include <stddef.h> #include <stdio.h> #include <sys/types.h> #include <dirent.h>

int main (void){ DIR *dp; struct dirent *ep;

dp = opendir ("./"); if (dp != NULL){ while (ep = readdir (dp)) puts (ep->d_name);

(void) closedir (dp); } else perror ("Couldn't open the directory");

return 0; }

2008-12-1 cs3320 39

Reading Directory Information:

getdents()

  • int getdents(int fd, struct dirent* buf, int structSize)
  • Reads the directory file with descriptor fd from its current position and fills structure pointed to by buf with the next entry.
  • Synopsis #include <unistd.h> #include <linux/types.h> #include <linux/dirent.h> #include <linux/unistd.h>

2008-12-1 cs3320 40

#include linux/unistd.h #include <errno.h> int getdents(unsigned int fd, struct dirent *dirp, unsigned int count);

  • Description
  • This is not the function you are interested in. Look at readdir (3) for the POSIX conforming C library interface. This page documents the bare kernel system call interface. The system call getdents () reads several dirent structures from the directory pointed at by fd into the memory area pointed to by dirp. The parameter count is the size of the memory area.
  • The dirent structure is declared as follows:
  • struct dirent { long d_ino; /* inode number / off_t d_off; / offset to next dirent / unsigned short d_reclen; / length of this dirent / char d_name [NAME_MAX+1]; / filename (null-terminated) */ }

Reading Directory Information:

getdents()

• The dirent struct is defined in

/usr/include/sys/dirent.h and contains the

following fields:

– d_ino : the inode number

– d_off : the offset of the next directory entry

– d_reclen : length of the dirent struct

– d_name : the fileName

Reading Directory Information:

getdents()

• Returns length of the directory entry if

successful

– 0 if last directory entry has already been read

– -1 if error

• processDirectory function skips. and .. and uses

lseek to advance to the next directory entry

System call chmod()

• int chmod (const char* fileName, int mode)

• int fchmod (int fd, int mode)

• These change the mode of fileName to mode

(specified as octal; ex. 0600)

• Set user ID and set group ID flags have values 04000

2008-12-1 cs3320 43

g p g

and 02000 respectively

int main() {

int flag;

flag = chmod("test.txt",0600);

if (flag == -1) perror("problem setting mode");

struct tm{ int tm_sec; /* Seconds. [0-60] (1 leap second) / int tm_min; / Minutes. [0-59] / int tm_hour; / Hours. [0-23] / int tm_mday; / Day. [1-31] / int tm_mon; / Month. [0-11] / int tm_year; / Year - 1900. / int tm_wday; / Day of week. [0-6] / int tm_yday; / Days in year.[0-365] / int tm_isdst; / DST. [-1/0/1]*/

#ifdef __USE_BSD long int tm_gmtoff; /* Seconds east of UTC. */ __const char tm_zone; / Timezone abbreviation. / #else long int __tm_gmtoff; / Seconds east of UTC. */ __const char __tm_zone; / Timezone abbreviation. */ #endif };

2008-12-1 cs3320 44

  • NAME
  • strftime - format date and time
  • SYNOPSIS
  • #include <time.h>
  • size_t strftime(char *s, size_t max, const char *format,
  • const struct tm *tm);
  • DESCRIPTION
  • The strftime() function formats the broken-down time tm according to
  • the format specification format and places the result in the character
  • array s of size max.

2008-12-1 cs3320 45

• NAME

  • asctime, ctime, gmtime, localtime, mktime, asctime_r, ctime_r,
  • gmtime_r, localtime_r - transform date and time to broken-down time or
  • ASCII
  • SYNOPSIS
  • #include <time.h>
  • char *asctime(const struct tm *tm);
  • char *asctime_r(const struct tm *tm, char *buf);
  • char *ctime(const time_t *timep);
  • char *ctime_r(const time_t *timep, char *buf);
  • struct tm *gmtime(const time_t *timep);
  • struct tm *gmtime_r(const time_t *timep, struct tm *result);
  • struct tm *localtime(const time_t *timep);
  • struct tm *localtime_r(const time_t *timep, struct tm *result);
  • time_t mktime(struct tm *tm);
  • DESCRIPTION The ctime(), gmtime() and localtime() functions all take an argument of data type time_t which represents calendar time. When interpreted as an absolute time value, it represents the number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC). 2008-12-1 cs3320 46

Process Management

• Every process in UNIX has

– some code

– some data

– a stack

• 1) The parameters

1) The parameters

• 2) The address (on the stack) of the calling programs

stack frame

• 3) The return address--where to go when the function

returns

• 4) The automatic (local) variables

– a unique process ID (PID)

Init Process

• When UNIX starts (boots), there is only one process, called init ,

with process ID = 1.

  • The only way to create a new process is to duplicate an existing

process

– So init is the ancestor of all subsequent processes.

• Initially, init duplicates ( forks ) several times and each child

process replaces its code ( execs ) with the code of the

executable getty which is responsible for user logins.

Example Program with getpid()

#include <stdio.h> main () { int pid; printf ("I'm the original process with PID %d and PPID %d.\n", getpid (), getppid ()); pid = fork (); /* Duplicate. Child & parent continue from here / if (pid != 0) / pid is non-zero, so I must be the parent */ { printf ("I'm the parent process with PID %d and PPID %d.\n", getpid () getppid ());

2008-12-1 cs3320 55

getpid (), getppid ()); printf ("My child's PID is %d\n", pid); } else /* pid is zero, so I must be the child / { printf ("I'm the child process with PID %d and PPID %d.\n", getpid (), getppid ()); } printf ("PID %d terminates.\n", getpid () ); / Both processes execute this */ }

Example Program with getpid()

$ myfork

I'm the original process with PID 639 and PPID 416.

I'm the parent process with PID 639 and PPID 416.

My child's PID is 640

PID 639 terminates.

$ I'm the child process with PID 640 and PPID 1.

PID 640 terminates.

2008-12-1 cs3320 56

Orphan Processes

• If a parent process terminates before its child

terminates, the child process is automatically

adopted by the init process

• The following program shows this.

2008-12-1 cs3320 57

g p g

Example Program of Orphan

#include <stdio.h> main () { int pid; printf ("I'm the original process with PID %d and PPID %d.\n", getpid (), getppid ()); pid = fork (); /* Duplicate. Child & parent continue from here / if (pid != 0) / Branch based on return value from fork () / { / pid is non-zero, so I must be the parent */ printf ("I'm the parent process with PID %d and PPID %d.\n", getpid (), getppid ()); i tf ("M hild' PID i %d\ " id)

2008-12-1 cs3320 58

printf ("My child's PID is %d\n", pid); } else { /* pid is zero, so I must be the child / sleep (5); / Make sure that the parent terminates first / printf ("I'm the child process with PID %d and PPID %d.\n", getpid (), getppid ()); } printf ("PID %d terminates.\n", getpid () ); / Both processes execute this */ }

Example Program of Orphan

$ orphan

I'm the original process with PID 680 and PPID 416.

I'm the parent process with PID 680 and PPID 416.

My child's PID is 681

PID 680 terminates.

$ I'm the child process with PID 681 and PPID 1.

PID 681 terminates.

System Call exit()

• void exit(int status)

• When a child process terminates, it sends its

parent a SIGCHLD signal and waits for its

termination code (status) to be accepted.

– Only lower 8 bits of status are used; so value 0-

Only lower 8 bits of status are used; so value 0 255

• closes all of a process' file descriptors,

deallocates its code, data, and stack; then

terminates the process.

• A process which is waiting for its parent process to accept its

return code is called a zombie process.

• A parent accepts a child's termination code by executing wait()

System Call exit()

• The kernel makes sure that all of a terminating

process' children are adopted by init by setting

their PPID's to 1;

• init always accepts its children's termination

2008-12-1 cs3320 61

y p

code.

• exit() never returns

Example of exit()

% cat myexit.c

#include <stdio.h>

#include <stdlib.h> /* needed for exit */

main() {

printf("I am going to exit with status code 42\n");

exit(42);

2008-12-1 cs3320 62

% myexit

I am going to exit with status code 42

% echo status is $?

Zombie Processes

• A process cannot leave the system until parent

process accepts its termination code

– even if it has exit-ed

• If parent process is dead; init adopts process and

accepts code

• If the parent process is alive but is unwilling to accept

2008-12-1 cs3320 63

p p g p

the child's termination code

– because it never executes wait()

– the child process will remain a zombie process.

Zombie Processes

• Zombie processes do not take up system

resources

– But do use up an entry in the system's fixed-size

process table

2008-12-1 cs3320 64

– Too many zombie processes is a problem

Zombie Example

#include <stdio.h>

main () {

int pid;

pid = fork (); /* Duplicate */

/* Branch based on return value from fork () */

if (pid != 0) {

/* Never terminate, never execute a wait () */

while (1)

sleep (1000);

else {

exit (42); /* Exit with a silly number */

Zombie Example

$ zombie &

[1] 684

$ ps

684 p4 S 0:00 zombie

685 p4 Z 0:00 (zombie )

686 p4 R 0:00 ps

p p

$ kill 684

[1]+ Terminated zombie

$ ps

688 p4 R 0:00 ps

Differentiating a Process: exec

• Use the absolute or relative name

– int execl(const char* path, const char* arg0, ...,

const char* argn, NULL)

– int execv(const char* path, const char* argv[ ])

2008-12-1 cs3320 73

Differentiating a Process: exec

• Use $PATH variable to find the executable:

– int execlp(const char* path, const char* arg0, ...,

const char* argn, NULL)

– int execvp(const char* path, const char* argv[ ])

2008-12-1 cs3320 74

Differentiating a Process: exec

• argi or argv[i]: i th command line argument for

executable (arg0: name of executable)

• If executable is not found, -1 is returned

– otherwise the calling process replaces its code, data,

2008-12-1 cs3320 75

g p p , ,

and stack with those of the executable and starts

executing the new code

• A successful exec() never returns

Example Using execl()

#include <stdio.h> main () { printf ("I'm process %d and I'm about to exec an ls -l\n", getpid ()); execl ("/bin/ls", "ls", "-l", NULL); /* Execute ls */ printf ("This line should never be executed\n"); }

$ myexec I'm process 710 and I'm about to exec an ls l

2008-12-1 cs3320 76

I m process 710 and I m about to exec an ls -l total 38 -rw-rw-r-- 1 raj raj 187 Jul 22 20:24 alarm.c -rw-rw-r-- 1 raj raj 226 Jul 22 20:22 background.c -rw-rw-r-- 1 raj raj 284 Jul 22 20:22 mychdir.c -rw-rw-r-- 1 raj raj 2058 Jul 22 20:23 vount.c -rwxrwxr-x 1 raj raj 4174 Jul 24 12:08 zombie -rw-rw-r-- 1 raj raj 298 Jul 22 20:20 zombie.c

Changing Directories: chdir()

• Every process has a current working directory

– Used when processing a relative path name

– A child process inherits the current working directory

from its parent

• Example: when a utility is run from a shell, the

utility process inherits the shell's current working

directory

Changing Directories: chdir()

• int chdir(const char* pathname)

• Sets a process' current working directory to

pathname

• The process must have execute permission

The process must have execute permission

from the directory for chdir() to succeed

• chdir() returns

– -1 if it fails

– 0 if it succeeds

Example Using chdir()

#include <stdio.h>

main () {

/* Display current working directory */

system ("pwd");

/* Change working directory to root directory */

chdir ("/");

2008-12-1 cs3320 79

/* Display new working directory */

system ("pwd");

chdir ("/home/naveen"); /* Change again */

system ("pwd"); /* Display again */

$ mychdir

/home/raj/3320/ch

/home/naveen

Changing Priorities: nice()

• Child process inherits priority of parent process

• Can change the priority using nice()

• int nice(int delta)

• Adds delta to the priority

L l l f i it 20 t 19

2008-12-1 cs3320 80

– Legal values of priority -20 to +

– Only super user can change to negative priority.

– Smaller the priority value, faster the process will run.

Getting and Setting User and Group

IDs:

• The get functions always succeed

• The set methods will succeed only when

executed by super user or if id equals real or

effective id of the process.

2008-12-1 cs3320 81

p

uid_t getuid() uid_t setuid(uid_t id)

uid_t geteuid() uid_t seteuid(uid_t id)

gid_t getgid() uid_t setgid(gid_t id)

gid_t getegid() uid_t setegid(gid_t id)

Example Using fork() and exec()

• Executes a program in background

• Original process creates a child process to exec

the specified executable and terminates.

• The orphaned child process is adopted by init.

2008-12-1 cs3320 82

The orphaned child process is adopted by init.

Example Using fork() and exec()

#include <stdio.h>

main (int argc, char* argv[]) {

if (fork () == 0) /* Child */ {

/* Execute other program */

execvp (argv[1], &argv[1]);

fprintf (stderr, "Could not execute %s\n", argv[1]);

p ( , , g [ ]);

$ background gcc mywait.c

Review

• C commands here work with OS

• Error Handling

• File I/O and management

– open

– read

read

– write

– close

– stat