Chapter 13 Systems Programming. Systems Programming. Error Handling. Error Handling. Example: File I/O. Example: File I/O

Size: px
Start display at page:

Download "Chapter 13 Systems Programming. Systems Programming. Error Handling. Error Handling. Example: File I/O. Example: File I/O"

Transcription

1 Chapter 13 Systems Programming Graham Glass and King Ables, UNIX for Programmers and Users, Third Edition, Pearson Prentice Hall, 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: File Management (Fig. 13.1) Process Management (Fig. 13.2) Error Handling (Fig. 13.3) cs cs Error Handling Most system calls are capable of failing in some way. Example: open a file may fail because file does not exist! 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) /* 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 cs cs Example: File I/O #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); /* 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 cs cs3320 6

2 File Management System Calls: open, fcntl, read, write, lseek, unlink, close Typical sequence: open Each read() and write() invokes a system call! Close All data are processed as a series of bytes (no format) cs cs cs cs UNIX File cs cs

3 vmunix File I/O File A sequence of bytes Directory A file that includes info on how to find other files. dev console lp0 bin csh / lib libc.a usr include etc passwd File I/O Path name Absolute path name Start at the root / of the file system /user/john/filea Relative path name Start at the current directory which is an attribute of the process accessing the path name../dira/fileb Links Symbolic Link 4.3BSD A file containing the path name of another file can across file-system boundaries. Hard Link. or cs cs File I/O File Descriptor Non-negative integer returned by open() or creat(): 0.. OPEN_MAX Virtually un-bounded for SVR4 & 4.3+BSD Each descriptor has its own private set of properties file pointer (stores offset within file; changes on read/write/lseek) flag indicating if the file descriptor should be closed or not when process execs flag indicating if output to file should be appended to end of file or not others Per-process base POSIX.1 0: STDIN_FILENO, 1: STDOUT_FILENO, 2: STDERR_FILENO <unistd.h> Convention employed by the Unix shells and applications cs File I/O - File Manipulation Operations open, close, read, write, lseek, dup, fcntl, ioctl, trunc, rename, chmod, chown, mkdir, cd, opendir, readdir, closedir, etc. Read(4, ) sync data block data block i-node i-node i-node System In-core Open File v-node Tables of Table list Opened Files (per process) cs Typical File I/O Sequence int fd; /* file descriptor 0: std. in, 1: std. out, 2: std error*/ fd = open(filename,...); if (fd == -1) /* deal with error */ fcntl(fd,...) /* set IO flags if needed */ read(fd,...) /* read from file */ write(fd,...) /* write to file */ lseek(fd,...) /* seek within file */ close(fd); /* close file */ cs File I/O open #include <sys/types> #include <sys/stat.h> #include <fcntl.h> int open(const char*pathname, int mode, int permission); File/Path Name O_RDONLY, O_WRONLY, O_RDWR O_APPEND, O_TRUNC O_CREAT, O_EXCL O_NONBLOCK open(pathname, O_WRONLY O_CREAT O_TRUNC, mode) cs

4 What is the output of the following program? #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> int main() { int fd1, fd2; fd1 = open("foo1.txt", O_RDONLY, 0); close(fd1); fd2 = open("foo2.txt", O_RDONLY, 0); printf("fd2 = %d\n", fd2); exit(0); open always returns lowest unopened 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. 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 cs cs 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: 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 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 cs cs 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) cs cs

5 File size is 50 (bytes) a b c d e f g h i j \0 \0 \0 \0 \0 \ \0 \ A B C D E F G H I J \0 \ 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: 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 cs cs Suppose that foobar.txt consists of the 6 ASCII characters "foobar". Then what is the output of the following program? I/O Efficiency How do you move from home to dorm? int main() { int fd1, fd2; char c; fd1 = open("foobar.txt", O_RDONLY, 0); fd2 = open("foobar foobar.txt 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 cs cs 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 0 if success -1 if failure cs cs

6 Read(4, ) File I/O Sharing Tables of Opened Files (per process) Memory System Open File Table Disk In-core v-node list Table per process: file des flags, a pointer #include <sys/file.h> int flock(int fd, int operation); //LOCK_SH LOCK_EX LOCK_UN sync data block data block i-node i-node i-node System Call stat() int stat(const char* name, struct stat* buf) stat() fills the buffer buf with information about file name The stat structure is defined in /usr/include/sys/stat.h and includes the following fields: st_mode the permission flags st_uid the user ID st_gid the group ID st_size the file size st_atime the last access time st_mtime the last modification time st_ctime the last status-change time cs cs Macros in /usr/include/sys/stat.h S_ISDIR(st_mode) true if directory S_ISCHR(st_mode) true if file is a character special device S_ISBLK(st_mode) true if file is a block special device S_ISREG(st_mode) true if a regular file S_ISFIFO(st_mode) true if a pipe Variations of stat() lstat() : same as stat() except it returns information about the symbolic link itself rather than the file it refers to fstat() : same as stat() except it takes file descriptor as first parameter All return 0 if successful and -1 otherwise cs cs Example Using stat() Call updatestat() if the file is a regular file character special file, or block special file. Either adds or updates the file's status entry If status has changes, updateentry() is called to display file's new status The decoding of time is done using localtime() and asctime() Directory manipulation DIR * opendir (const char *dirname) struct dirent * readdir (DIR *dirstream) closedir cs cs

7 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: 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 cs 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: 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 cs Sample code #include <stddef.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; cs 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> #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) */ cs 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 cs cs

8 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 and 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 */ 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 ; cs cs 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 cs 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) cs Process Management Every process in UNIX has some code some data a stack 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 cs cs

9 Parent and Child Processes It is very common for a parent process to suspend itself until one of its child processes terminates. For example: Consider the way a shell process executes a utility in the foreground: The shell first duplicates itself using fork() The child shell process replaces its code with that of the utility using exec(). (Differentiates) The parent process waits for the child process to terminate using wait() When the child process terminates using exit(), the parent process is informed (using a signal) the parent process presents the user with the shell prompt to accept the next command fork() getpid() getppid() exit() wait() exec family System Calls cs cs System Call fork() pit_t fork(void) Causes a process to duplicate The child process is almost exactly a duplicate of the parent process inherits a copy of its parent's code, data, stack, open file descriptors, and signal tables The only difference is in the process IDs (pid) and parent process IDs (ppid) If fork() succeeds, it returns a value of 0 to the child process and the PID of the child process to the parent. If fork() fails, it returns a -1 to the parent process and the child process is not created cs Sample code #include <stdlib.h> int main(){ pid_t child_pid; /* storage place for the pid of the child process, and its exit status. */ int child_status, i=10,j=10; child_pid = fork(); /* lets fork off a child process... */ switch (child_pid) { /* check what the fork() call actually did */ case -1: /* fork() failed */ perror("fork"); /* print a system-defined error message */ exit(1); case 0: /* fork() succeeded, we're inside the child process */ j=i+10; printf("hello world from child! i=%d, j=%d\n,i,j); exit(0); /* here the CHILD process exits, not the parent. */ default: /* fork() succeeded, we're inside the parent process */ j=j+5; wait(&child_status); /* wait till the child process exits */ printf("hello world from parent! i=%d, j=%d\n",i,j); /* parent's process code may continue here... */ return 0; As before, suppose foobar.txt consists of 6 ASCII characters "foobar". Then what is the output of the following program? int main() { int fd; char c; fd = open("foobar.txt", O_RDONLY, 0); if(fork() == 0) {read(fd, &c, 1); exit(0); wait(null); read(fd, &c, 1); printf("c = %c\n", c); exit(0); System Call getpid() pid_t getpid(void) pid_t getppid(void) Return the process' ID and parent process ID respectively They always succeed The PPID value for process with ID=1 is 1 Child inherit s the parent s descriptor table. So child and parent share an open file table entry. Hence they share a file position. c= o cs cs

10 Example Program with getpid() 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 ()); 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 cs cs Orphan Processes If a parent process terminates before its child terminates, the child process is automatically adopted by the init process The following gprogram shows this. Example Program of Orphan 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 ()); 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 */ cs cs 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 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() cs cs

11 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 code. exit() never returns Example of exit() % cat myexit.c #include <stdlib.h> /* needed for exit */ main() { printf("i am going to exit with status code 42\n"); exit(42); % myexit I am going to exit with status code 42 % echo status is $? cs cs 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 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 Too many zombie processes is a problem cs cs main () { int pid; pid = fork (); /* Duplicate */ Zombie Example /* 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 <zombie>) 686 p4 R 0:00 ps $ kill 684 [1]+ Terminated zombie $ ps 688 p4 R 0:00 ps $ cs cs

12 Waiting for a Child: wait() pid_t wait(int *status) causes a process to suspend until one of its child processes terminates. A successful call to wait() returns the PID of the child process that terminated places a status code into status Waiting for a Child: wait() Status code is encoded as: If the rightmost byte of status is zero the leftmost byte contains the low 8 bits of the value returned by the child's exit() or return() call If the rightmost t byte of status t is non-zero the rightmost 7 bits are equal to the Signal Number that caused the child to terminate the last bit is set to 1 if the child core dumped cs cs Waiting for a Child: wait() If a process executes a wait() and has no children, wait() returns immediately with a value of -1 If a process executes a wait(), And one or more children are already zombies, Then wait() returns immediately with the status of one of the zombies Example Program using wait() main () { int pid, status, childpid; printf ("I'm the parent process and my PID is %d\n", getpid()); pid = fork (); /* Duplicate */ if (pid!= 0) /* Branch based on return value from fork () */ { printf ("I'm the parent process with PID %d and PPID %d\n", getpid (), getppid ()); /* Wait for a child to terminate. */ childpid = wait (&status); printf("a child with PID %d terminated with exit code %d\n", childpid, status >> 8); else { printf ("I'm the child process with PID %d and PPID %d\n", getpid (), getppid ()); exit (42); /* Exit with a silly number */ printf ("PID %d terminates\n", getpid () ); cs cs Example Program using wait() $ mywait I'm the parent process and my PID is 695 I'm the parent process with PID 695 and PPID 418 I'm the child process with PID 696 and PPID 695 A child with PID 696 terminated with exit code 42 PID 695 terminates Differentiating a Process: exec With the exec family, a process replaces Its current code Data Stack PID and PPID stay the same Only the code that the process is executing changes cs cs

13 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[ ]) 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[ ]) cs cs Differentiating a Process: exec argi or argv[i]: ith command line argument for executable (arg0: name of executable) If executable is not found, -1 is returned otherwise the calling gprocess replaces its code, data, and stack with those of the executable and starts executing the new code A successful exec() never returns Example Using execl() 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 Im process 710 and I'm Im 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 cs cs 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 from the directory for chdir() to succeed chdir() returns -1 if it fails 0 if it succeeds cs cs

14 Example Using chdir() main () { /* Display current working directory */ system ("pwd"); /* Change working directory to root directory */ chdir ("/"); /* Display new working directory */ system ("pwd"); chdir ("/home/naveen"); /* Change again */ system ("pwd"); /* Display again */ $ mychdir /home/raj/3320/ch12 / /home/naveen $ cs 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 Legal values of priority it -20 to +19 Only super user can change to negative priority. Smaller the priority value, faster the process will run cs 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. 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. uid_t getuid() uid_t geteuid() gid_t getgid() gid_t getegid() uid_t setuid(uid_t id) uid_t seteuid(uid_t id) uid_t setgid(gid_t id) uid_t setegid(gid_t id) cs cs Example Using fork() and exec() 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]); $ background gcc mywait.c Review C commands here work with OS Error Handling File I/O and management open read write close stat cs cs

15 System Commands fork() getpid() exit() wait() exec Review Review Working with directories and file entries getdents chown chmod Process Management chdir nice cs cs

UNIX System Calls. Sys Calls versus Library Func

UNIX System Calls. Sys Calls versus Library Func UNIX System Calls Entry points to the kernel Provide services to the processes One feature that cannot be changed Definitions are in C For most system calls a function with the same name exists in the

More information

Hyo-bong Son Computer Systems Laboratory Sungkyunkwan University

Hyo-bong Son Computer Systems Laboratory Sungkyunkwan University File I/O Hyo-bong Son (proshb@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Unix Files A Unix file is a sequence of m bytes: B 0, B 1,..., B k,..., B m-1 All I/O

More information

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto Ricardo Rocha Department of Computer Science Faculty of Sciences University of Porto For more information please consult Advanced Programming in the UNIX Environment, 3rd Edition, W. Richard Stevens and

More information

CSC 271 Software I: Utilities and Internals

CSC 271 Software I: Utilities and Internals CSC 271 Software I: Utilities and Internals Lecture 13 : An Introduction to File I/O in Linux File Descriptors All system calls for I/O operations refer to open files using a file descriptor (a nonnegative

More information

I/O OPERATIONS. UNIX Programming 2014 Fall by Euiseong Seo

I/O OPERATIONS. UNIX Programming 2014 Fall by Euiseong Seo I/O OPERATIONS UNIX Programming 2014 Fall by Euiseong Seo Files Files that contain a stream of bytes are called regular files Regular files can be any of followings ASCII text Data Executable code Shell

More information

I/O OPERATIONS. UNIX Programming 2014 Fall by Euiseong Seo

I/O OPERATIONS. UNIX Programming 2014 Fall by Euiseong Seo I/O OPERATIONS UNIX Programming 2014 Fall by Euiseong Seo Files Files that contain a stream of bytes are called regular files Regular files can be any of followings ASCII text Data Executable code Shell

More information

CSE 333 SECTION 3. POSIX I/O Functions

CSE 333 SECTION 3. POSIX I/O Functions CSE 333 SECTION 3 POSIX I/O Functions Administrivia Questions (?) HW1 Due Tonight Exercise 7 due Monday (out later today) POSIX Portable Operating System Interface Family of standards specified by the

More information

Lecture 21 Systems Programming in C

Lecture 21 Systems Programming in C Lecture 21 Systems Programming in C A C program can invoke UNIX system calls directly. A system call can be defined as a request to the operating system to do something on behalf of the program. During

More information

System Calls and I/O Appendix. Copyright : University of Illinois CS 241 Staff 1

System Calls and I/O Appendix. Copyright : University of Illinois CS 241 Staff 1 System Calls and I/O Appendix Copyright : University of Illinois CS 241 Staff 1 More System Calls Directory and File System Management s = mkdir(name, mode) Create a new directory s = rmdir(name) s = link(name,

More information

System Calls. Library Functions Vs. System Calls. Library Functions Vs. System Calls

System Calls. Library Functions Vs. System Calls. Library Functions Vs. System Calls System Calls Library Functions Vs. System Calls A library function: Ordinary function that resides in a library external to the calling program. A call to a library function is just like any other function

More information

Chp1 Introduction. Introduction. Objective. Logging In. Shell. Briefly describe services provided by various versions of the UNIX operating system.

Chp1 Introduction. Introduction. Objective. Logging In. Shell. Briefly describe services provided by various versions of the UNIX operating system. Chp1 Objective Briefly describe services provided by various versions of the UNIX operating system. Logging In /etc/passwd local machine or NIS DB root:x:0:1:super-user:/root:/bin/tcsh Login-name, encrypted

More information

Operating System Labs. Yuanbin Wu

Operating System Labs. Yuanbin Wu Operating System Labs Yuanbin Wu cs@ecnu Annoucement Next Monday (28 Sept): We will have a lecture @ 4-302, 15:00-16:30 DON'T GO TO THE LABORATORY BUILDING! TA email update: ecnucchuang@163.com ecnucchuang@126.com

More information

Preview. System Call. System Call. System Call. System Call. Library Functions 9/20/2018. System Call

Preview. System Call. System Call. System Call. System Call. Library Functions 9/20/2018. System Call Preview File Descriptors for a Process for Managing Files write read open close lseek A system call is a request for the operating system to do something on behalf of the user's program. The system calls

More information

CS 201. Files and I/O. Gerson Robboy Portland State University

CS 201. Files and I/O. Gerson Robboy Portland State University CS 201 Files and I/O Gerson Robboy Portland State University A Typical Hardware System CPU chip register file ALU system bus memory bus bus interface I/O bridge main memory USB controller graphics adapter

More information

CSE 333 SECTION 3. POSIX I/O Functions

CSE 333 SECTION 3. POSIX I/O Functions CSE 333 SECTION 3 POSIX I/O Functions Administrivia Questions (?) HW1 Due Tonight HW2 Due Thursday, July 19 th Midterm on Monday, July 23 th 10:50-11:50 in TBD (And regular exercises in between) POSIX

More information

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 15: Unix interface: low-level interface Cristina Nita-Rotaru Lecture 15/Fall 2013 1 Streams Recap Higher-level interface, layered on top of the primitive file descriptor

More information

Lecture files in /home/hwang/cs375/lecture05 on csserver.

Lecture files in /home/hwang/cs375/lecture05 on csserver. Lecture 5 Lecture files in /home/hwang/cs375/lecture05 on csserver. cp -r /home/hwang/cs375/lecture05. scp -r user@csserver.evansville.edu:/home/hwang/cs375/lecture05. Project 1 posted, due next Thursday

More information

Interacting with Unix

Interacting with Unix Interacting with Unix Synopsis Getting the Process ID #include pid_t getpid(void); Example: #include #include int main(){ pid_t n = getpid(); printf("process id is %d\n",

More information

CSC209F Midterm (L0101) Fall 1999 University of Toronto Department of Computer Science

CSC209F Midterm (L0101) Fall 1999 University of Toronto Department of Computer Science CSC209F Midterm (L0101) Fall 1999 University of Toronto Department of Computer Science Date: October 26, 1999 Time: 1:10 pm Duration: 50 minutes Notes: 1. This is a closed book test, no aids are allowed.

More information

Operating Systems. Processes

Operating Systems. Processes Operating Systems Processes 1 Process Concept Process a program in execution; process execution progress in sequential fashion Program vs. Process Program is passive entity stored on disk (executable file),

More information

Operating System Labs. Yuanbin Wu

Operating System Labs. Yuanbin Wu Operating System Labs Yuanbin Wu CS@ECNU Operating System Labs Project 3 Oral test Handin your slides Time Project 4 Due: 6 Dec Code Experiment report Operating System Labs Overview of file system File

More information

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto Ricardo Rocha Department of Computer Science Faculty of Sciences University of Porto For more information please consult Advanced Programming in the UNIX Environment, 3rd Edition, W. Richard Stevens and

More information

OPERATING SYSTEMS: Lesson 2: Operating System Services

OPERATING SYSTEMS: Lesson 2: Operating System Services OPERATING SYSTEMS: Lesson 2: Operating System Services Jesús Carretero Pérez David Expósito Singh José Daniel García Sánchez Francisco Javier García Blas Florin Isaila 1 Goals To understand what an operating

More information

Outline. OS Interface to Devices. System Input/Output. CSCI 4061 Introduction to Operating Systems. System I/O and Files. Instructor: Abhishek Chandra

Outline. OS Interface to Devices. System Input/Output. CSCI 4061 Introduction to Operating Systems. System I/O and Files. Instructor: Abhishek Chandra Outline CSCI 6 Introduction to Operating Systems System I/O and Files File I/O operations File Descriptors and redirection Pipes and FIFOs Instructor: Abhishek Chandra 2 System Input/Output Hardware devices:

More information

Lecture 3. Introduction to Unix Systems Programming: Unix File I/O System Calls

Lecture 3. Introduction to Unix Systems Programming: Unix File I/O System Calls Lecture 3 Introduction to Unix Systems Programming: Unix File I/O System Calls 1 Unix File I/O 2 Unix System Calls System calls are low level functions the operating system makes available to applications

More information

File I/0. Advanced Programming in the UNIX Environment

File I/0. Advanced Programming in the UNIX Environment File I/0 Advanced Programming in the UNIX Environment File Descriptors Created and managed by the UNIX kernel. Created using open or creat system call. Used to refer to an open file UNIX System shells

More information

Systems Programming. COSC Software Tools. Systems Programming. High-Level vs. Low-Level. High-Level vs. Low-Level.

Systems Programming. COSC Software Tools. Systems Programming. High-Level vs. Low-Level. High-Level vs. Low-Level. Systems Programming COSC 2031 - Software Tools Systems Programming (K+R Ch. 7, G+A Ch. 12) The interfaces we use to work with the operating system In this case: Unix Programming at a lower-level Systems

More information

Examination C++ Programming

Examination C++ Programming LUND INSTITUTE OF TECHNOLOGY 1(8) Department of Computer Science Examination C++ Programming 2011 08 20, 8.00 13.00 Aid at the exam: one C++ book. The copies of the lecture slides are not allowed. You

More information

Last Week: ! Efficiency read/write. ! The File. ! File pointer. ! File control/access. This Week: ! How to program with directories

Last Week: ! Efficiency read/write. ! The File. ! File pointer. ! File control/access. This Week: ! How to program with directories Overview Unix System Programming Directories and File System Last Week:! Efficiency read/write! The File! File pointer! File control/access This Week:! How to program with directories! Brief introduction

More information

CS , Spring Sample Exam 3

CS , Spring Sample Exam 3 Andrew login ID: Full Name: CS 15-123, Spring 2010 Sample Exam 3 Mon. April 6, 2009 Instructions: Make sure that your exam is not missing any sheets, then write your full name and Andrew login ID on the

More information

UNIX System Programming

UNIX System Programming File I/O 경희대학교컴퓨터공학과 조진성 UNIX System Programming File in UNIX n Unified interface for all I/Os in UNIX ü Regular(normal) files in file system ü Special files for devices terminal, keyboard, mouse, tape,

More information

Important Dates. October 27 th Homework 2 Due. October 29 th Midterm

Important Dates. October 27 th Homework 2 Due. October 29 th Midterm CSE333 SECTION 5 Important Dates October 27 th Homework 2 Due October 29 th Midterm String API vs. Byte API Recall: Strings are character arrays terminated by \0 The String API (functions that start with

More information

CSC209H Lecture 6. Dan Zingaro. February 11, 2015

CSC209H Lecture 6. Dan Zingaro. February 11, 2015 CSC209H Lecture 6 Dan Zingaro February 11, 2015 Zombie Children (Kerrisk 26.2) As with every other process, a child process terminates with an exit status This exit status is often of interest to the parent

More information

PRACTICAL NO : 1. AIM: To study various file management system calls in UNIX.

PRACTICAL NO : 1. AIM: To study various file management system calls in UNIX. PRACTICAL NO : 1 AIM: To study various file management system calls in UNIX. Write a program to implement 1. Create a file 2. Delete a file 3. Link a file 4. Copy one file to another file 5. Read contents

More information

Parents and Children

Parents and Children 1 Process Identifiers Every process apart from the PID also has a PUID and a PGID. There are two types of PUID and PGID: real and effective. The real PUID is always equal to the user running the process

More information

Process Creation in UNIX

Process Creation in UNIX Process Creation in UNIX int fork() create a child process identical to parent Child process has a copy of the address space of the parent process On success: Both parent and child continue execution at

More information

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 16: Process and Signals Cristina Nita-Rotaru Lecture 16/ Fall 2013 1 Processes in UNIX UNIX identifies processes via a unique Process ID Each process also knows its parent

More information

Operating Systems. Lecture 06. System Calls (Exec, Open, Read, Write) Inter-process Communication in Unix/Linux (PIPE), Use of PIPE on command line

Operating Systems. Lecture 06. System Calls (Exec, Open, Read, Write) Inter-process Communication in Unix/Linux (PIPE), Use of PIPE on command line Operating Systems Lecture 06 System Calls (Exec, Open, Read, Write) Inter-process Communication in Unix/Linux (PIPE), Use of PIPE on command line March 04, 2013 exec() Typically the exec system call is

More information

CMSC 216 Introduction to Computer Systems Lecture 17 Process Control and System-Level I/O

CMSC 216 Introduction to Computer Systems Lecture 17 Process Control and System-Level I/O CMSC 216 Introduction to Computer Systems Lecture 17 Process Control and System-Level I/O Sections 8.2-8.5, Bryant and O'Hallaron PROCESS CONTROL (CONT.) CMSC 216 - Wood, Sussman, Herman, Plane 2 Signals

More information

Operating System Labs. Yuanbin Wu

Operating System Labs. Yuanbin Wu Operating System Labs Yuanbin Wu CS@ECNU Operating System Labs Project 4 (multi-thread & lock): Due: 10 Dec Code & experiment report 18 Dec. Oral test of project 4, 9:30am Lectures: Q&A Project 5: Due:

More information

All the scoring jobs will be done by script

All the scoring jobs will be done by script File I/O Prof. Jin-Soo Kim( jinsookim@skku.edu) TA Sanghoon Han(sanghoon.han@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Announcement (1) All the scoring jobs

More information

Contents. NOTICE & Programming Assignment #1. QnA about last exercise. File IO exercise

Contents. NOTICE & Programming Assignment #1. QnA about last exercise. File IO exercise File I/O Examples Prof. Jin-Soo Kim(jinsookim@skku.edu) TA - Dong-Yun Lee(dylee@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Contents NOTICE & Programming Assignment

More information

which maintain a name to inode mapping which is convenient for people to use. All le objects are

which maintain a name to inode mapping which is convenient for people to use. All le objects are UNIX Directory Organization UNIX directories are simple (generally ASCII) les which maain a name to inode mapping which is convenient for people to use. All le objects are represented by one or more names

More information

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst Operating Systems CMPSCI 377 Spring 2017 Mark Corner University of Massachusetts Amherst Clicker Question #1 For a sequential workload, the limiting factor for a disk system is likely: (A) The speed of

More information

All the scoring jobs will be done by script

All the scoring jobs will be done by script File I/O Prof. Jinkyu Jeong( jinkyu@skku.edu) TA-Seokha Shin(seokha.shin@csl.skku.edu) TA-Jinhong Kim( jinhong.kim@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu

More information

Advanced Unix/Linux System Program. Instructor: William W.Y. Hsu

Advanced Unix/Linux System Program. Instructor: William W.Y. Hsu Advanced Unix/Linux System Program Instructor: William W.Y. Hsu CONTENTS File I/O, File Sharing 3/15/2018 INTRODUCTION TO COMPETITIVE PROGRAMMING 2 Recall simple-cat.c... /* * Stripped down version of

More information

Unix File and I/O. Outline. Storing Information. File Systems. (USP Chapters 4 and 5) Instructor: Dr. Tongping Liu

Unix File and I/O. Outline. Storing Information. File Systems. (USP Chapters 4 and 5) Instructor: Dr. Tongping Liu Outline Unix File and I/O (USP Chapters 4 and 5) Instructor: Dr. Tongping Liu Basics of File Systems Directory and Unix File System: inode UNIX I/O System Calls: open, close, read, write, ioctl File Representations:

More information

System Programming. Process Control II

System Programming. Process Control II Content : by Dr. B. Boufama School of Computer Science University of Windsor Instructor: Dr. A. Habed adlane@cs.uwindsor.ca http://cs.uwindsor.ca/ adlane/60-256 Content Content 1 Terminating a process

More information

System Programming. Process Control III

System Programming. Process Control III Content : by Dr. B. Boufama School of Computer Science University of Windsor Instructor: Dr. A. Habed adlane@cs.uwindsor.ca http://cs.uwindsor.ca/ adlane/60-256 Content Content 1 Differentiating a process:

More information

System- Level I/O. Andrew Case. Slides adapted from Jinyang Li, Randy Bryant and Dave O Hallaron

System- Level I/O. Andrew Case. Slides adapted from Jinyang Li, Randy Bryant and Dave O Hallaron System- Level I/O Andrew Case Slides adapted from Jinyang Li, Randy Bryant and Dave O Hallaron 1 Unix I/O and Files UNIX abstracts many things into files (just a series of bytes) All I/O devices are represented

More information

Operating systems. Lecture 7

Operating systems. Lecture 7 Operating systems. Lecture 7 Michał Goliński 2018-11-13 Introduction Recall Plan for today History of C/C++ Compiler on the command line Automating builds with make CPU protection rings system calls pointers

More information

Recitation 8: Tshlab + VM

Recitation 8: Tshlab + VM Recitation 8: Tshlab + VM Instructor: TAs 1 Outline Labs Signals IO Virtual Memory 2 TshLab and MallocLab TshLab due Tuesday MallocLab is released immediately after Start early Do the checkpoint first,

More information

File I/O. Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University Embedded Software Lab.

File I/O. Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University  Embedded Software Lab. 1 File I/O Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University http://nyx.skku.ac.kr Unix files 2 A Unix file is a sequence of m bytes: B 0, B 1,..., B k,..., B m-1 All I/O devices are represented

More information

Windows architecture. user. mode. Env. subsystems. Executive. Device drivers Kernel. kernel. mode HAL. Hardware. Process B. Process C.

Windows architecture. user. mode. Env. subsystems. Executive. Device drivers Kernel. kernel. mode HAL. Hardware. Process B. Process C. Structure Unix architecture users Functions of the System tools (shell, editors, compilers, ) standard library System call Standard library (printf, fork, ) OS kernel: processes, memory management, file

More information

Overview. Unix System Programming. Outline. Directory Implementation. Directory Implementation. Directory Structure. Directories & Continuation

Overview. Unix System Programming. Outline. Directory Implementation. Directory Implementation. Directory Structure. Directories & Continuation Overview Unix System Programming Directories & Continuation Maria Hybinette, UGA 1 Last Week: Efficiency read/write The File File pointer File control/access Permissions, Meta Data, Ownership, umask, holes

More information

UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING SOFTWARE ENGINEERING DEPARTMENT

UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING SOFTWARE ENGINEERING DEPARTMENT OPERATING SYSTEM LAB #06 & 07 System Calls In UNIX System Call: A system call is just what its name implies a request for the operating system to do something on behalf of the user s program. Process related

More information

Lecture 8: Unix Pipes and Signals (Feb 10, 2005) Yap

Lecture 8: Unix Pipes and Signals (Feb 10, 2005) Yap Lecture 8: Unix Pipes and Signals (Feb 10, 2005) Yap February 17, 2005 1 ADMIN Our Grader will be Mr. Chien-I Liao (cil217@nyu.edu). Today s Lecture, we will go into some details of Unix pipes and Signals.

More information

CMPS 105 Systems Programming. Prof. Darrell Long E2.371

CMPS 105 Systems Programming. Prof. Darrell Long E2.371 + CMPS 105 Systems Programming Prof. Darrell Long E2.371 darrell@ucsc.edu + Chapter 3: File I/O 2 + File I/O 3 n What attributes do files need? n Data storage n Byte stream n Named n Non-volatile n Shared

More information

File I/O. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

File I/O. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University File I/O Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Unix Files A Unix file is a sequence of m bytes: B 0, B 1,..., B k,..., B m-1 All I/O devices

More information

Lecture 23: System-Level I/O

Lecture 23: System-Level I/O CSCI-UA.0201-001/2 Computer Systems Organization Lecture 23: System-Level I/O Mohamed Zahran (aka Z) mzahran@cs.nyu.edu http://www.mzahran.com Some slides adapted (and slightly modified) from: Clark Barrett

More information

structs as arguments

structs as arguments Structs A collection of related data items struct record { char name[maxname]; int count; ; /* The semicolon is important! It terminates the declaration. */ struct record rec1; /*allocates space for the

More information

CS 33. Files Part 2. CS33 Intro to Computer Systems XXI 1 Copyright 2018 Thomas W. Doeppner. All rights reserved.

CS 33. Files Part 2. CS33 Intro to Computer Systems XXI 1 Copyright 2018 Thomas W. Doeppner. All rights reserved. CS 33 Files Part 2 CS33 Intro to Computer Systems XXI 1 Copyright 2018 Thomas W. Doeppner. All rights reserved. Directories unix etc home pro dev passwd motd twd unix... slide1 slide2 CS33 Intro to Computer

More information

Files and Directories Filesystems from a user s perspective

Files and Directories Filesystems from a user s perspective Files and Directories Filesystems from a user s perspective Unix Filesystems Seminar Alexander Holupirek Database and Information Systems Group Department of Computer & Information Science University of

More information

CSC 1600 Unix Processes. Goals of This Lecture

CSC 1600 Unix Processes. Goals of This Lecture CSC 1600 Unix Processes q Processes Goals of This Lecture q Process vs. program q Context switching q Creating a new process q fork: process creates a new child process q wait: parent waits for child process

More information

CSCI-E28 Lecture 3 Outline. Directories, File Attributes, Bits, File Operations. Write our own versions of Unix programs

CSCI-E28 Lecture 3 Outline. Directories, File Attributes, Bits, File Operations. Write our own versions of Unix programs CSCI-E28 Lecture 3 Outline Topics: Approach: Directories, File Attributes, Bits, File Operations Write our own versions of Unix programs Featured Commands: ls, ls -l Main Ideas: Adirectory is a list of

More information

Lesson 2. process id = 1000 text data i = 5 pid = 1200

Lesson 2. process id = 1000 text data i = 5 pid = 1200 Lesson 2 fork: create a new process. The new process (child process) is almost an exact copy of the calling process (parent process). In this method we create an hierarchy structure for the processes,

More information

CSC209 Fall Karen Reid 1

CSC209 Fall Karen Reid 1 ' & ) ) #$ "! How user programs interact with the Operating System. Somehow we need to convert a program into machine code (object code). A compiler passes over a whole program before translating it into

More information

File Systems. q Files and directories q Sharing and protection q File & directory implementation

File Systems. q Files and directories q Sharing and protection q File & directory implementation File Systems q Files and directories q Sharing and protection q File & directory implementation Files and file systems Most computer applications need to Store large amounts of data; larger than their

More information

Fall 2015 COMP Operating Systems. Lab #3

Fall 2015 COMP Operating Systems. Lab #3 Fall 2015 COMP 3511 Operating Systems Lab #3 Outline n Operating System Debugging, Generation and System Boot n Review Questions n Process Control n UNIX fork() and Examples on fork() n exec family: execute

More information

Process Management! Goals of this Lecture!

Process Management! Goals of this Lecture! Process Management! 1 Goals of this Lecture! Help you learn about:" Creating new processes" Programmatically redirecting stdin, stdout, and stderr" Unix system-level functions for I/O" The Unix stream

More information

Unix-Linux 2. Unix is supposed to leave room in the process table for a superuser process that could be used to kill errant processes.

Unix-Linux 2. Unix is supposed to leave room in the process table for a superuser process that could be used to kill errant processes. Unix-Linux 2 fork( ) system call is successful parent suspended child created fork( ) returns child pid to parent fork( ) returns zero value to child; zero is the pid of the swapper/scheduler process both

More information

CS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017

CS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017 CS 471 Operating Systems Yue Cheng George Mason University Fall 2017 Review: RAID 2 RAID o Idea: Build an awesome disk from small, cheap disks o Metrics: Capacity, performance, reliability 3 RAID o Idea:

More information

Fall 2017 :: CSE 306. File Systems Basics. Nima Honarmand

Fall 2017 :: CSE 306. File Systems Basics. Nima Honarmand File Systems Basics Nima Honarmand File and inode File: user-level abstraction of storage (and other) devices Sequence of bytes inode: internal OS data structure representing a file inode stands for index

More information

Naked C Lecture 6. File Operations and System Calls

Naked C Lecture 6. File Operations and System Calls Naked C Lecture 6 File Operations and System Calls 20 August 2012 Libc and Linking Libc is the standard C library Provides most of the basic functionality that we've been using String functions, fork,

More information

Operating System Labs. Yuanbin Wu

Operating System Labs. Yuanbin Wu Operating System Labs Yuanbin Wu cs@ecnu Announcement Project 1 due 21:00, Oct. 8 Operating System Labs Introduction of I/O operations Project 1 Sorting Operating System Labs Manipulate I/O System call

More information

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 17: Processes, Pipes, and Signals Cristina Nita-Rotaru Lecture 17/ Fall 2013 1 Processes in UNIX UNIX identifies processes via a unique Process ID Each process also knows

More information

CSci 4061 Introduction to Operating Systems. File Systems: Basics

CSci 4061 Introduction to Operating Systems. File Systems: Basics CSci 4061 Introduction to Operating Systems File Systems: Basics File as Abstraction Naming a File creat/open ( path/name, ); Links: files with multiple names Each name is an alias #include

More information

CSI 402 Lecture 11 (Unix Discussion on Files continued) 11 1 / 19

CSI 402 Lecture 11 (Unix Discussion on Files continued) 11 1 / 19 CSI 402 Lecture 11 (Unix Discussion on Files continued) 11 1 / 19 User and Group IDs Ref: Chapter 3 of [HGS]. Each user is given an ID (integer) called uid. (Most system programs use uid instead of the

More information

File Descriptors and Piping

File Descriptors and Piping File Descriptors and Piping CSC209: Software Tools and Systems Programming Furkan Alaca & Paul Vrbik University of Toronto Mississauga https://mcs.utm.utoronto.ca/~209/ Week 8 Today s topics File Descriptors

More information

Contents. Programming Assignment 0 review & NOTICE. File IO & File IO exercise. What will be next project?

Contents. Programming Assignment 0 review & NOTICE. File IO & File IO exercise. What will be next project? File I/O Prof. Jin-Soo Kim(jinsookim@skku.edu) TA - Dong-Yun Lee(dylee@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Contents Programming Assignment 0 review & NOTICE

More information

The course that gives CMU its Zip! I/O Nov 15, 2001

The course that gives CMU its Zip! I/O Nov 15, 2001 15-213 The course that gives CMU its Zip! I/O Nov 15, 2001 Topics Files Unix I/O Standard I/O A typical hardware system CPU chip register file ALU system bus memory bus bus interface I/O bridge main memory

More information

File and Directories. Advanced Programming in the UNIX Environment

File and Directories. Advanced Programming in the UNIX Environment File and Directories Advanced Programming in the UNIX Environment stat Function #include int stat(const char *restrict pathname, struct stat *restrict buf ); int fstat(int fd, struct stat

More information

Processes often need to communicate. CSCB09: Software Tools and Systems Programming. Solution: Pipes. Recall: I/O mechanisms in C

Processes often need to communicate. CSCB09: Software Tools and Systems Programming. Solution: Pipes. Recall: I/O mechanisms in C 2017-03-06 Processes often need to communicate CSCB09: Software Tools and Systems Programming E.g. consider a shell pipeline: ps wc l ps needs to send its output to wc E.g. the different worker processes

More information

Chapter 4 - Files and Directories. Information about files and directories Management of files and directories

Chapter 4 - Files and Directories. Information about files and directories Management of files and directories Chapter 4 - Files and Directories Information about files and directories Management of files and directories File Systems Unix File Systems UFS - original FS FFS - Berkeley ext/ext2/ext3/ext4 - Linux

More information

System Programming. Introduction to Unix

System Programming. Introduction to Unix Content : by Dr. B. Boufama School of Computer Science University of Windsor Instructor: Dr. A. Habed adlane@cs.uwindsor.ca http://cs.uwindsor.ca/ adlane/60-256 Content Content 1 Introduction 2 3 Introduction

More information

Files and Directories

Files and Directories Files and Directories Administrative * HW# 1 Due this week Goals: Understand the file system concepts * files, links, and directories * device independent interface Topics: * 3.0 Device independence *

More information

System Calls and I/O. CS 241 January 27, Copyright : University of Illinois CS 241 Staff 1

System Calls and I/O. CS 241 January 27, Copyright : University of Illinois CS 241 Staff 1 System Calls and I/O CS 241 January 27, 2012 Copyright : University of Illinois CS 241 Staff 1 This lecture Goals Get you familiar with necessary basic system & I/O calls to do programming Things covered

More information

Introduction. Files. 3. UNIX provides a simple and consistent interface to operating system services and to devices. Directories

Introduction. Files. 3. UNIX provides a simple and consistent interface to operating system services and to devices. Directories Working With Files Introduction Files 1. In UNIX system or UNIX-like system, all input and output are done by reading or writing files, because all peripheral devices, even keyboard and screen are files

More information

Outline. File Systems. File System Structure. CSCI 4061 Introduction to Operating Systems

Outline. File Systems. File System Structure. CSCI 4061 Introduction to Operating Systems Outline CSCI 4061 Introduction to Operating Systems Instructor: Abhishek Chandra File Systems Directories File and directory operations Inodes and metadata Links 2 File Systems An organized collection

More information

Preview. Process Control. What is process? Process identifier The fork() System Call File Sharing Race Condition. COSC350 System Software, Fall

Preview. Process Control. What is process? Process identifier The fork() System Call File Sharing Race Condition. COSC350 System Software, Fall Preview Process Control What is process? Process identifier The fork() System Call File Sharing Race Condition COSC350 System Software, Fall 2015 1 Von Neumann Computer Architecture: An integrated set

More information

Preview. Review. System Data Files (Password File) System Data Files (Password File) System Data Files (Password File)

Preview. Review. System Data Files (Password File) System Data Files (Password File) System Data Files (Password File) Review Preview link(), unlink() System Call remove(), rename() System Call Symbolic Links Symbolic link to directory Symbolic link to a executable file symlink() System Call File Times utime() System Call

More information

CMPSC 311- Introduction to Systems Programming Module: Input/Output

CMPSC 311- Introduction to Systems Programming Module: Input/Output CMPSC 311- Introduction to Systems Programming Module: Input/Output Professor Patrick McDaniel Fall 2014 Input/Out Input/output is the process of moving bytes into and out of the process space. terminal/keyboard

More information

Maria Hybinette, UGA. ! One easy way to communicate is to use files. ! File descriptors. 3 Maria Hybinette, UGA. ! Simple example: who sort

Maria Hybinette, UGA. ! One easy way to communicate is to use files. ! File descriptors. 3 Maria Hybinette, UGA. ! Simple example: who sort Two Communicating Processes Hello Gunnar CSCI 6730/ 4730 Operating Systems Process Chat Maria A Hi Nice to Hear from you Process Chat Gunnar B Dup & Concept that we want to implement 2 On the path to communication

More information

CPSC 341 OS & Networks. Processes. Dr. Yingwu Zhu

CPSC 341 OS & Networks. Processes. Dr. Yingwu Zhu CPSC 341 OS & Networks Processes Dr. Yingwu Zhu Process Concept Process a program in execution What is not a process? -- program on a disk A process is an active object, but a program is just a file It

More information

UNIX System Programming. Overview. 1. A UNIX System. 2. Processes (review) 2.1. Context. Pipes/FIFOs

UNIX System Programming. Overview. 1. A UNIX System. 2. Processes (review) 2.1. Context. Pipes/FIFOs UNIX System Programming Pipes/FIFOs Overview 1. A UNIX System (review) 2. Processes (review) Objectives Look at UNIX support for interprocess communication (IPC) on a single machine Review processes pipes,

More information

Chapter 10. The UNIX System Interface

Chapter 10. The UNIX System Interface 프로그래밍 1 1 Chapter 10. The UNIX System Interface June, 2016 Dept. of software Dankook University http://embedded.dankook.ac.kr/~baeksj 파일의개념 (1/5) 2 파일의정의 사용자가이용할수있는데이터의실체레코드들의집합이라고정의 파일의필요성 데이터의효율적인저장및검색을위해파일단위구분

More information

File I/O - Filesystems from a user s perspective

File I/O - Filesystems from a user s perspective File I/O - Filesystems from a user s perspective Unix Filesystems Seminar Alexander Holupirek Database and Information Systems Group Department of Computer & Information Science University of Konstanz

More information

What Is Operating System? Operating Systems, System Calls, and Buffered I/O. Academic Computers in 1983 and Operating System

What Is Operating System? Operating Systems, System Calls, and Buffered I/O. Academic Computers in 1983 and Operating System What Is Operating System? Operating Systems, System Calls, and Buffered I/O emacs gcc Browser DVD Player Operating System CS 217 1 Abstraction of hardware Virtualization Protection and security 2 Academic

More information

Input and Output System Calls

Input and Output System Calls Chapter 2 Input and Output System Calls Internal UNIX System Calls & Libraries Using C --- 1011 OBJECTIVES Upon completion of this unit, you will be able to: Describe the characteristics of a file Open

More information

CSCI 4500/8506 Operating Systems Some UNIX System Calls, Library, and PThreads Functions

CSCI 4500/8506 Operating Systems Some UNIX System Calls, Library, and PThreads Functions CSCI 4500/8506 Operating Systems Some UNIX System Calls, Library, and PThreads Functions Described below is a subset of UNIX system calls, library functions, and Pthreads (that is, POSIX Threads) functions.

More information