UNIVERSITY OF TORONTO Faculty of Arts and Science. St. George Campus APRIL 2017 EXAMINATIONS. CSC 209H1S Instructor: Karen Reid Duration: 3 hours

Similar documents
UNIVERSITY OF TORONTO Faculty of Arts and Science. St. George Campus DECEMBER 2017 EXAMINATIONS. CSC 209H1F Liu, Reid 3 hours. No Examination Aids

UNIVERSITY OF TORONTO Faculty of Arts and Science. St. George Campus APRIL 2016 EXAMINATIONS. CSC 209H1S Michelle Craig, David Liu 3 hours

UNIVERSITY OF TORONTO Faculty of Arts and Science. St. George Campus APRIL 2012 EXAMINATIONS

[6 marks] All parts of this question assume the following C statement. Parts (b) through (e) assume a variable called ptrs.

CSC 209H1 S 2012 Midterm Test Duration 50 minutes Aids allowed: none. Student Number: # 1: / 7

Student Number: Instructor: Reid Section: L0101 (10:10-11:00am)

CSC 209H1 S 2012 Midterm Test Duration 50 minutes Aids allowed: none. Student Number: # 1: / 6

Process Creation in UNIX

Student Number: Instructor: Reid Section: L5101 (6:10-7:00pm)

CSC209H1S Day Midterm Solutions Winter 2010

Student Number: Instructor: Reid Section: L0201 (12:10-1:00pm)

UNIVERSITY OF TORONTO SCARBOROUGH Computer and Mathematical Sciences. APRIL 2016 EXAMINATIONS CSCB09H3S Software Tools & Systems Programming

COMP 2355 Introduction to Systems Programming

UNIX System Calls. Sys Calls versus Library Func

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

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

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

Operating System Labs. Yuanbin Wu

Good Luck! Marking Guide. APRIL 2014 Final Exam CSC 209H5S

CSE 333 SECTION 3. POSIX I/O Functions

structs as arguments

Recitation 8: Tshlab + VM

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

Process Management! Goals of this Lecture!

A Socket Example. Haris Andrianakis & Angelos Stavrou George Mason University

File Descriptors and Piping

CSC209H Lecture 9. Dan Zingaro. March 11, 2015

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

CSC209H Lecture 6. Dan Zingaro. February 11, 2015

Hyo-bong Son Computer Systems Laboratory Sungkyunkwan University

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

CSE 333 SECTION 3. POSIX I/O Functions

CSC209F Midterm (L5101) Fall 1998 University of Toronto Department of Computer Science

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

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

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files. Compiler vs.

TCP: Three-way handshake

UNIX Kernel. UNIX History

Question 1. Part (a) Part (b) Part (c) Part (d) Part (e) Part (f) APRIL 2012 Final Examination Solutions CSC 209H1S

Pipes and FIFOs. Woo-Yeong Jeong Computer Systems Laboratory Sungkyunkwan University

CS 3113 Introduction to Operating Systems Midterm October 11, 2018

CS 3113 Introduction to Operating Systems Midterm October 11, 2018

Creating a Shell or Command Interperter Program CSCI411 Lab

CSC209H Lecture 10. Dan Zingaro. March 18, 2015

CSC209 Review. Yeah! We made it!

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

ECE 650 Systems Programming & Engineering. Spring 2018

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

CS 25200: Systems Programming. Lecture 14: Files, Fork, and Pipes

Inter-Process Communication. Disclaimer: some slides are adopted from the book authors slides with permission 1

Operating System Labs. Yuanbin Wu

Unix Network Programming Chapter 4. Elementary TCP Sockets 광운대학교컴퓨터과학과 정보통신연구실 석사과정안중현

Oral. Total. Dated Sign (2) (5) (3) (2)

File Systems Overview. Jin-Soo Kim ( Computer Systems Laboratory Sungkyunkwan University

everything is a file main.c a.out /dev/sda1 /dev/tty2 /proc/cpuinfo file descriptor int

Final Exam. Fall Semester 2016 KAIST EE209 Programming Structures for Electrical Engineering. Name: Student ID:

CONCURRENCY MODEL. UNIX Programming 2014 Fall by Euiseong Seo

Process Management 1

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

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

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

628 Lecture Notes Week 4

CSMC 412. Computer Networks Prof. Ashok K Agrawala Ashok Agrawala Set 2. September 15 CMSC417 Set 2 1

OS COMPONENTS OVERVIEW OF UNIX FILE I/O. CS124 Operating Systems Fall , Lecture 2

Preview. Interprocess Communication with Pipe. Pipe from the Parent to the child Pipe from the child to the parent FIFO popen() with r Popen() with w

Process Management! Goals of this Lecture!

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

Tutorial on Socket Programming

SOFTWARE ARCHITECTURE 3. SHELL

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

25.2 Opening and Closing a File

Student Number: Lab day, time: Instructor: Bianca Schroeder

15-213/ Final Exam Notes Sheet Spring 2013!

CS360 Midterm 2 Spring, 2016 James S. Plank March 10, 2016

OS Lab Tutorial 1. Spawning processes Shared memory

UNIX System Programming

Contents. IPC (Inter-Process Communication) Representation of open files in kernel I/O redirection Anonymous Pipe Named Pipe (FIFO)

CSC 271 Software I: Utilities and Internals

Computer Networks Prof. Ashok K. Agrawala

UNIX Sockets. Developed for the Azera Group By: Joseph D. Fournier B.Sc.E.E., M.Sc.E.E.

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

Communication. Sockets (Haviland Ch. 10)

FILE SYSTEMS. Jo, Heeseung

Contents. PA1 review and introduction to PA2. IPC (Inter-Process Communication) Exercise. I/O redirection Pipes FIFOs

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

CSE 124 Discussion Section Sockets Programming 10/10/17

Final Exam 1 /12 2 /12 3 /10 4 /7 5 /4 6 /10 7 /8 8 /9 9 /8 10 /11 11 /8 12 /10 13 /9 14 /13 15 /10 16 /10 17 /12. Faculty of Computer Science

COM324 System Programming. Midterm Exam

15-213/18-243, Spring 2011 Exam 2

Outline. Distributed Computer Systems. Socket Basics An end-point for a IP network connection. Ports. Sockets and the OS. Transport Layer.

CSC209S Midterm (L0101) Spring 1999 University of Toronto Department of Computer Science

Socket Programming TCP UDP

Socket Programming. #In the name of Allah. Computer Engineering Department Sharif University of Technology CE443- Computer Networks

The Shell, System Calls, Processes, and Basic Inter-Process Communication

Concurrent Servers Dec 2, 2009"

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

Hyo-bong Son Computer Systems Laboratory Sungkyunkwan University

Transcription:

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science St. George Campus APRIL 2017 EXAMINATIONS CSC 209H1S Instructor: Karen Reid Duration: 3 hours PLEASE HAND IN Examination Aids: One double-sided 8.5x11 sheet of paper. No electronic aids. Student Number: Last (Family) Name(s): First (Given) Name(s): Do not turn this page until you have received the signal to start. (In the meantime, please fill out the identification section above, and read the instructions below carefully.) Marking Guide This final examination consists of 9 questions on 20 pages. A mark of at least 31 out of 79 on this exam is required to pass this course. When you receive the signal to start, please make sure that your copy of the examination is complete. You are not required to add any #include lines, and unless otherwise specified, you may assume a reasonable maximum for character arrays or other structures. For shell programs, you do not need to include the #!/bin/sh. Error checking is not necessary unless it is required for correctness. Answers that contain a mixture of correct and incorrect or irrelevant statements will not receive full marks. # 1: /12 # 2: / 6 # 3: / 6 # 4: / 8 # 5: / 8 # 6: / 5 # 7: /15 # 8: / 9 # 9: /10 Good Luck! TOTAL: /79 Page 1

CSC 209H1S Final Examination APRIL 2017 Question 1. Part (a) TRUE FALSE [12 marks] [8 marks] Circle the correct answer for the statements below. You can send a signal to an unrelated process. (An unrelated process is neither an ancestor nor descendant.) TRUE FALSE Given the following call to accept, the socket sockfd should be closed as soon as a new client has been accepted because it is no longer needed. int accept(int sockfd, struct sockaddr *client, socklen_t *addrlen); TRUE FALSE The code below has a memory leak. void helper(int *arr, int size) { arr = malloc(sizeof(int) * size); TRUE FALSE All character arrays must be null-terminated. TRUE FALSE If a process tries to read from an open pipe before there is any data in the pipe, it could get an error. TRUE FALSE Open file descriptors are inherited across a fork call but not across an exec call. TRUE FALSE The reason we don t see the shell prompt appear when running a program in the foreground is that the program we are running in the foreground is a child of the shell, and the shell has called wait. TRUE FALSE If we have two files that are hard links for the same file, they cannot have different permissions or a diferent owner. Part (b) [2 marks] Consider the following code fragment. int age[5] = {4, 70, 52, 18, 16; int *p = &age[2]; Check the boxes of the statements below that are true after the code fragment has run. The following is an illegal statement: age[0] = p[0]; The values in the array after the execution of the statement age[0] = p[0]; are {52, 70, 52, 18, 16 The expression *(a+3)could lead to a segmentation fault The expression *(p+3) could lead to a segmentation fault Page 2 of 20

APRIL 2017 Final Examination CSC 209H1S Part (c) [2 marks] Given the following code snippet, check the box for line or lines that would not lead to any problems with the code regardless of the value of argv[1]. if(argc < 2) { return 1; char name[30]; // missing code that modifies name such that it is a valid string strncat(name, argv[1], 30); strncat(name, argv[1], strlen(argv[1]) + 1); strncat(name, argv[1], 30-strlen(name) + 1); strncat(name, argv[1], 30-strlen(name) - 1); strncat(name, argv[1], strlen(name) + 1); Page 3 of 20

CSC 209H1S Final Examination APRIL 2017 Question 2. Part (a) [2 marks] [6 marks] In the two s complement representation of a negative number, the highest bit has the value 1 for negative numbers and 0 for positive numbers. For example, in an 8-bit number 1111 1001 is the two s complement representation for -7, while 0000 0111 is the two s complement representation for 7. status is an int that holds a two s complement number as the last 8 bits. Fill in the conditional expression below so that the if statement executes correctly. Note that you only need the information above to solve the problem. unsigned int status; // missing code to assigns to status a two s complement value in the lowest 8 bits if( ) { printf("the value in num is negative\n"); else { printf("the value in num is positive\n"); Part (b) [4 marks] Write a shell program that takes a filename as an argument and prints the full path to each location in the $PATH variable where the file is found. You may not use any programs in your solution (such as where, ls, find etc) other than tr which is explained below. Suppose the program is called mywhere, then here is an example. reid@wolf$./mywhere python /usr/local/bin/python /usr/bin/python Recall that $PATH is a colon-separated list of absolute paths. To turn it into a space-separated list, we use a program called tr that reads from standard input and translates all characters of its first argument to its second argument. For example the following line will output /usr/bin /sbin /bin echo /usr/bin:/sbin:/bin tr : " " Step 1: Write one line that will assign to a shell variable dirs the result of using tr on $PATH. Step 2: Using the list in dirs complete the program described above. Page 4 of 20

APRIL 2017 Final Examination CSC 209H1S Question 3. [6 marks] Below is a simple C program. In the space below the program, draw a complete memory diagram showing all of the memory allocated immediately before get ext returns. Clearly distinguish between the different sections of memory (stack, heap, global), as well as different stack frames. You must show where each variable is stored, but make sure it s clear in your diagram what is a variable name vs. the value stored for that variable. You may show a pointer value by drawing an arrow to the location in memory with that address, or may make up address values. char *get_ext(char *filename){ char *ptr = strchr(filename,. ); char *ext = malloc(strlen(ptr+1) + 1); strncpy(ext, ptr+1, strlen(ptr+1)+1); // Draw memory at this point in the program. return ext; int main() { char name[8] = "prog.py"; char *e = get_ext(name); printf("%s %s\n", name, e); return 0; Page 5 of 20

CSC 209H1S Final Examination APRIL 2017 Question 4. [8 marks] Each of the code fragments below has a problem. Explain what is wrong, and then fix the code by printing neatly on the code itself. Note that failing to check for errors on system calls is not the problem. Part (a) [1 mark] if(argc > 2) { char *name = malloc(strlen(argv[2]) + 1); name = argv[2]; Part (b) [1 mark] if(argc > 2) { char s[30] = argv[1]; s[0] = A ; Part (c) [1 mark] int *firstfive(int *A) { int vals[5]; for(int i = 0; i < 5; i++) { vals[i] = A[i]; return vals; Part (d) [2 marks] struct point{ int x; int y; ; //Return the sum of the coordinates of p and negate their values int sum_and_flip(struct point p) { int sum = p.x + p.y; p.x = p.x * -1; p.y = p.y * -1; return sum; Page 6 of 20

APRIL 2017 Final Examination CSC 209H1S Part (e) [1 mark] int status; if(wait(&status)!= -1) { printf("status is %d", WEXITSTATUS(status)); Part (f) [2 marks] Note that failing to check for errors is not the problem with the code below. int main() { char buf[8]; int fd[2]; pipe(fd); int r = fork(); if(r == 0) { close(fd[1]); while(read(fd[0], buf, 8) == 8) { printf("buf=%s\n", buf); exit(0); else { close(fd[0]); strcpy(buf, "Hi "); write(fd[1], buf, 8); wait(null); exit(0); return 1; Page 7 of 20

CSC 209H1S Final Examination APRIL 2017 Question 5. Part (a) [6 marks] [8 marks] The program below creates a directory from the first argument to main. Using only the lines of code provided in the table on the right, fill in the code in the table on the left so that when the program receives the SIGINT signal, the permissions of the directory are changed to 0700 and prints a message notifying the user that the permissions have changed before the program terminates. label code line Use the labels in the table below to clearly identify the lines you have chosen. Note that some incorrect lines have been added as options, and that extra slots have been added to the table on the left. An exmple has been given for you, using line z. int main(int argc, char **argv) { mkdir(argv[1], 0400); z printf("directory created\n"); label code line a chmod(path, 0700); b exit(0); c exit(1); d printf("changed %s\n", path); e char *path; f path = NULL; g path = argv[1]; h path = malloc(strlen(argv[1])+1); i sa.sa_flags = 0; k sa.sa_handler = &fixperm; m sa.sa_handler = fixperm; n sigaction(sigint, &sa, NULL); o sigaction(sigint, sa, NULL); p sigemptyset(&sa.sa_mask); s struct sigaction sa; t int fixperm(char *path) { u int fixperm(int code) { w void fixperm(char *path) { x void fixperm(int code) { y z printf("directory created\n"); // The rest of the program is omitted. // No code will be added below this comment. Page 8 of 20

APRIL 2017 Final Examination CSC 209H1S Part (b) [2 marks] Add the error checking for the call to chmod(path, 0700) so that it prints an error message and terminates the program with a value of 1. Page 9 of 20

CSC 209H1S Final Examination APRIL 2017 Question 6. [5 marks] Consider the following program that compiles and runs to completion without error. int main() { int r = fork(); if(r == 0) { printf("first\n"); r = fork(); if(r == 0) { printf("second\n"); exit(0); else { printf("third\n"); printf("fourth\n"); if(wait(null)!= -1) { printf("fifth\n"); exit(0); Part (a) [1 mark] How many processes are run including the process that calls main? Part (b) [4 marks] Check the boxes for the statements below that are true. First must be displayed first Second must be displayed after First (not necessarily immediately after) Fourth is displayed three times Second could be displayed after Fourth (not necessarily immediately after) Second and Third could be displayed in either order The process that prints Second also prints First The second last line displayed must be Fifth The last line displayed must be Fifth Page 10 of 20

APRIL 2017 Final Examination CSC 209H1S Question 7. [15 marks] The goal of this question is to write a program called redir that allows standard input and/or standard output to be redirected from or to a file. Command line arguments are specified below. Square brackets mean that the argument is optional. redir [-i infile] [-o outfile] prog [arg1... ] Examples: redir ls redir -i names sort redir -o listing.txt ls -l redir -i data.csv -o names cut -f 1 -d "," redir -o names -i data.csv cut -f 1 -d "," No redirection. The program ls is run. The program sort is run and input is redirected from the file called names The program ls is run with the argument -l, and the output is redirected to the file listing.txt The program cut is run with the arguments -f 1 -d ",". Input is redirected from data.csv, and output is redirected to the file names (Same as previous.) Part (a) [2 marks] Rewrite the first four examples as shell commands. In other words, how would you achieve the same results without using the program redir? redir ls redir -i names sort redir -o listing.txt ls -l redir -i data.csv -o names cut -f 1 -d "," Page 11 of 20

CSC 209H1S Final Examination APRIL 2017 Part (b) [7 marks] Complete the function below that parses the command line arguments. It returns the index into argv that holds the name of program to run, and sets the input and output file names as the last two parameters (where appropriate) so that they may be used in the main program when read options returns. Do not use getopt. Assume all arguments are passed correctly, so you don t need to consider too few arguments or other incorrect options. int read_options(int argc, char **argv,, ) { /* Fill in the initialization for infile and outfile, and the arguments to read_options * * infile is set to the name of the input file to redirect from if the * -i option was used, and is set to NULL if input is not redirected. * outfile is set to the name of the output file to redirect to if the * -o option was used, and is set to NULL if output is not redirected. * index is set to the index into the argv array that holds the name of the * program to run. */ int main(int argc, char **argv) { char *infile = ; char *outfile = ; int index = read_options(argc, argv,, ); Page 12 of 20

APRIL 2017 Final Examination CSC 209H1S Part (c) [6 marks] Given that the command line arguments have been parsed correctly, so that the variables from the the previous question have their correct values, complete the program as specified. Page 13 of 20

CSC 209H1S Final Examination APRIL 2017 Question 8. [9 marks] Suppose every machine in our labs is running a load monitoring server that is listening for connections on port 33333. When a client connects to the server, the server will send an integer (in network byte order) representing the load on the machine, and will then close the socket. Your task is to complete the code below for a client that will connect to each of the lab machines in turn and store the load values in an array. The host ip addresses are stored in a file with one address per line with unix line endings( \n ). Example: 128.100.32.2 128.100.32.23 128.100.32.37 Assume there will never be more than MAXHOSTS IP addresses in the file. #define MAXNAME 64 #define MAXHOSTS 30 struct machine { char *host_ip[maxname]; int load; ; // The ip address read from the file int main(int argc, char* argv[]) { struct machine lab[maxhosts]; Part (a) [4 marks] Populate the host ip fields in the array lab with the IP addresses from a file called hosts. Any unused array elements should have the host_ip field set to the empty string. Remember to remove newline character from the input. Page 14 of 20

APRIL 2017 Final Examination CSC 209H1S Part (b) [5 marks] Now, for each host IP address in the lab array, create a socket connection to the server, store the integer (in the correct format) received from the server in the load field, and close the socket. Some of the setup is done for you below. Recall that inet pton can be used to convert the string form of the host IP address into the form needed by the sin addr field of the struct sockaddr in. int soc; struct sockaddr_in peer; peer.sin_family = PF_INET; peer.sin_port = htons(port); printf("port = %d\n", PORT); Page 15 of 20

CSC 209H1S Final Examination APRIL 2017 Question 9. [10 marks] Consider the following parts of a server that will manage multiple clients. Note that error checking has been removed for brevity and some parts of the program are missing. The questions below assume that the missing components are correctly implemented. struct client { int fd; char *name; struct client *next; ; static struct client *addclient(struct client *top, int fd, char *name) { struct client *p = malloc(sizeof(struct client)); p->fd = fd; p->name = malloc(strlen(name)+1); strncpy(p->name, name, strlen(name)+1); p->next = top; top = p; return top; int main(int argc, char **argv) { // Assume all variables are correctly declared and initialized // The appropriate calls have been made to set up the socket. FD_ZERO(&readset); FD_SET(listenfd, &readset); maxfd = listenfd; while (1) { n = select(maxfd + 1, &readset, NULL, NULL, NULL); if (FD_ISSET(listenfd, &readset)){ clientfd = accept(listenfd, (struct sockaddr *)&q, &len); char buffer[maxname]; read(clientfd, buffer, MAXNAME); printf("connection from %s\n", buffer); head = addclient(head, clientfd, buffer); // code to check each client that is ready to read follow Page 16 of 20

APRIL 2017 Final Examination CSC 209H1S Part (a) [4 marks] When the server is run we notice that the program runs, but blocks forever in select even though new connections are coming in and there is always more data ready to read from all connected clients. This is the result of two problems in the code. Explain the problem and fix it in the code above. (Lack of error checking is not the problem.) Part (b) [3 marks] Now that the problem in the previous question is fixed, the server correctly handles multiple connections as long as the clients don t experience any delays. But sometimes, when one client is slow, it seems to slow everything down. Explain the problem and how to fix it. (You don t need to write the code.) Part (c) [3 marks] Complete the function below to free the client list: void free_list(struct client *top) { Page 17 of 20

CSC 209H1S Final Examination APRIL 2017 This page can be used if you need additional space for your answers. Total Marks = 79 Page 18 of 20

APRIL 2017 Final Examination CSC 209H1S C function prototypes and structs: int accept(int sock, struct sockaddr *addr, int *addrlen) int bind(int sock, struct sockaddr *addr, int addrlen) int chmod(const char *path, mode t mode) int close(int fd) int closedir(dir *dir) int connect(int sock, struct sockaddr *addr, int addrlen) int dup2(int oldfd, int newfd) int execlp(const char *file, char *argv0,..., (char *)0) int execvp(const char *file, char *argv[]) int fclose(file *stream) int FD ISSET(int fd, fd set *fds) void FD SET(int fd, fd set *fds) void FD CLR(int fd, fd set *fds) void FD ZERO(fd set *fds) char *fgets(char *s, int n, FILE *stream) int fileno(file *stream) pid t fork(void) FILE *fopen(const char *file, const char *mode) size t fread(void *ptr, size t size, size t nmemb, FILE *stream); int fseek(file *stream, long offset, int whence); /* SEEK_SET, SEEK_CUR, or SEEK_END*/ size t fwrite(const void *ptr, size t size, size t nmemb, FILE *stream); unsigned long int htonl(unsigned long int hostlong) /* 4 bytes */ unsigned short int htons(unsigned short int hostshort) /* 2 bytes */ char *index(const char *s, int c) int inet pton(int af, const char *src, void *dst); /*af=pf\_inet; pass in address of sin\_addr field as dst */ int kill(int pid, int signo) int listen(int sock, int n) int mkdir(const char *pathname, mode t mode) unsigned long int ntohl(unsigned long int netlong) unsigned short int ntohs(unsigned short int netshort) int open(const char *path, int oflag) /* oflag is O_WRONLY O_CREAT for write and O_RDONLY for read */ DIR *opendir(const char *name) int pclose(file *stream) int pipe(int filedes[2]) FILE *popen(char *cmdstr, char *mode) ssize t read(int d, void *buf, size t nbytes); struct dirent *readdir(dir *dir) int select(int maxfdp1, fd set *readfds, fd set *writefds, fd set *exceptfds, struct timeval *timeout) int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact) /* actions include SIG_DFL and SIG_IGN */ unsigned int sleep(unsigned int seconds) int socket(int family, int type, int protocol) /* family=pf INET, type=sock STREAM, protocol=0 */ int sprintf(char *s, const char *format,...) int stat(const char *file name, struct stat *buf) char *strchr(const char *s, int c) size t strlen(const char *s) char *strncat(char *dest, const char *src, size t n) int strncmp(const char *s1, const char *s2, size t n) char *strncpy(char *dest, const char *src, size t n) char *strrchr(const char *s, int c) int wait(int *status) int waitpid(int pid, int *stat, int options) /* options = 0 or WNOHANG*/ ssize t write(int d, const void *buf, size t nbytes); Page 19 of 20

CSC 209H1S Final Examination APRIL 2017 WIFEXITED(status) WIFSIGNALED(status) WIFSTOPPED(status) WEXITSTATUS(status) WTERMSIG(status) WSTOPSIG(status) Useful structs struct sigaction { void (*sa handler)(int); sigset t sa mask; int sa flags; struct hostent { char *h name; // name of host char **h aliases; // alias list int h addrtype; // host address type int h length; // length of address char *h addr; // address struct sockaddr in { sa family t sin family; unsigned short int sin port; struct in addr sin addr; unsigned char pad[8]; /*Unused*/ struct stat { dev t st dev; /* ID of device containing file */ ino t st ino; /* inode number */ mode t st mode; /* protection */ nlink t st nlink; /* number of hard links */ uid t st uid; /* user ID of owner */ gid t st gid; /* group ID of owner */ dev t st rdev; /* device ID (if special file) */ off t st size; /* total size, in bytes */ blksize t st blksize; /* blocksize for file system I/O */ blkcnt t st blocks; /* number of 512B blocks allocated */ time t st atime; /* time of last access */ time t st mtime; /* time of last modification */ time t st ctime; /* time of last status change */ ; Shell comparison operators Shell Description -d filename Exists as a directory -f filename Exists as a regular file. -r filename Exists as a readable file -w filename Exists as a writable file. -x filename Exists as an executable file. -z string True if empty string str1 = str2 True if str1 equals str2 str1!= str2 True if str1 not equal to str2 int1 -eq int2 True if int1 equals int2 -ne, -gt, -lt, -le For numbers!=, >, >=, <, <= For strings -a, -o And, or. Useful shell commands: cat, cut, echo, ls, read, sort, uniq, wc ps aux - prints the list of currently running processes grep (returns 0 if match is found, 1 if no match was found, and 2 if there was an error) grep -v displays lines that do not match diff (returns 0 if the files are the same, and 1 if the files differ) $0 Script name $# Number of positional parameters $* List of all positional parameters $? Exit value of previously executed command Page 20 of 20 End of Examination