0% found this document useful (0 votes)
13 views14 pages

University of Toronto Mississauca April 2018 Final Examination CSG209H5S

The document is the instructions for a final exam for the course CSC209H5S Software Tools and Systems Programming. It provides information about the exam such as its duration of 2 hours, that no examination aids are permitted, and instructions on how to complete and submit the exam. Students are reminded that possessing unauthorized aids during the exam could result in an academic offense. Electronic devices must be turned off, sealed in a clear plastic bag, and placed under the student's desk for the duration of the exam.

Uploaded by

Dude Nugget
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views14 pages

University of Toronto Mississauca April 2018 Final Examination CSG209H5S

The document is the instructions for a final exam for the course CSC209H5S Software Tools and Systems Programming. It provides information about the exam such as its duration of 2 hours, that no examination aids are permitted, and instructions on how to complete and submit the exam. Students are reminded that possessing unauthorized aids during the exam could result in an academic offense. Electronic devices must be turned off, sealed in a clear plastic bag, and placed under the student's desk for the duration of the exam.

Uploaded by

Dude Nugget
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

UNIVERSITY OF TORONTO MISSISSAUCA

APRIL 2018 FINAL EXAMINATION


CSG209H5S
Software Tools and Systems Programming
Instructors: Dema, Petersen
Duration: 2 hours
Examination Aids: None

Student Number: i i i i_11 i i i

UtorJD: .. . . _^

Family Name(s):

Given Name(s):

The University of Toronto Mississauga and you, as a student, share a commitment to academic integrity. You are
remmded that you may be charged with an academic offence for possessing any miauthorized aids during the writing
of an exam. Clear, sealable, plastic bags have been provided for all electronic devices wifch storage, including but not
limited to: ceU pliones, SMART devices, tablets, laptops, calculators, and MP3 players. Please turn off all devices,
seal them in the bag provided, and place the bag under your desk for the duration of fche examination. You will nofc
be able to touch the bag or ifcs contents until the exam is over.

If) during an exam, any of these items are found on your person or in the area of your desk other than in the clear,
sealable, plastic bag, you may be charged with an academic offence. A typical penalty for an academic offence may
cause you to fail the course.

Please note, once tills exam h&s begun, you CANNOT re-write it.

Do not turn this page until you have received the signal to start.
In tlie meantime, please read the instructions below carefully.

This final examiuafcion paper consists of 6 questions on 16 pages (includmg this


one). Whe.n you -receive the signal to start, please make sure that your copy of the
final examination is complete.

Comments are not required, although they may lielp us mark your answers.

Error checking is required throughout tlie test.

You do not need to provide include statements.

If you use any space for rough work, indicate clearly what you want marked.

You may tear the API page off the back of this exam.

Page I of 16 Good Luck! CONT'D. .


April 2018 Final Examination CSC209H5S

Question 1. [3 MARKS]
Programming Tools

Part (a) [1 MARK]


How does make decide which targets need to be built? Your answer should discuss dependencies.

Part (b) [1 MARK]


In sssignm.en.t 3, gdb became more difficult to use. Explain what feature of assignment 3 made gdb more
difficult to use and explain what you had to do to continue using it effectively.

Part (c) [1 MARK]


You've just run your program f copy and you see the dreaded message "Segment at ion fault: II".
Briefly explain how you would use gdb to identify what has caused the error.

Page 2 of 16 COMT'D. ..
April 2018 Final Examination CSC209H5S

Question 2. Memoiy [6 MARKS]

The questions in this secfciou feature a small piece of code and a blank diagram repreeenfciug memory. Your
task is to fill in the diagram so th&t it represents the v^ables and values in the code. Place tlie name
and type of each variable to the left of the diagram, place muneric and strhig values into the appropriate
locationsj iu the diagram (subdividing the boxes when necessary), and represent addresses as arrows from
the pointer location to the locafciou they pomfc to.
Pointers are 8 bytes. lutegers are 4 bytes. If the value of a variable is unspecified, write "???".

In. some cases, variables are men.tkmed without a type. You will need to infer the type of the variable but
may assume that it is located on the stack.
There are 8 points assigned to questions in this section, but the whole section is only worth 6. The
additional points are a bonus because there are some small details tha-fc would be easy to uuss.

Part (a) [4 MARKS]

Type
and Name Memory

Stack

char *name == "Ilir";


alias s= &aame;
fc = >K(*alias + 4);

Heap

Data and
Cocfe

bytes

Page 3 of 16 CONT'D. . .
April 2018 Final Examination CSC209H5S

Part (b) [4 MARKS]


Assume that the malloc call in the following code succeeds.

int vals£4] = {0, 1, 2, 3>;


i = malloc(sizeof(int) * 4);
*i = 42;

Type
and Name Memory

Stack

Heap

Data and
Code

8 bytes

Page 4 of 16 CONT'D.
April 2018 Final Examination CSC209H5S

Question 3. Processes [12 MARKS]

For the first two questions, consider this command which was executed hi the shell:

,/pfact 27 | grep "Number" » nuKi_filters.txt

Recall fchafc the pipe operator redirects STDOUT froiii the process on. fch.e left to STDIN for the process on the
right and that "»" redirects STDQUT to a file but appends to the file, rather than. overwriting it.

Part (a) [1 MARK]


Assume that the shell process s PID is 100 and that any processes created wUl be assigned the PIDs 101,
102, 103, etc., and assume that pfact is a working instance of the assignment 3 code. How many processes
are created, and for each process, what is the PID of its parent and the PID(s) of ifcs children, if any?

Part (b) [3 MARKS]


Focus ou. the first pfact process and grep. Describe the work the shell process performs to create asid
connect the two. Name the system or library calls that are invoked, and specify their order.

Page 5 of 16 CONT'D. ..
April 2018 Final Examination CSC209H5S

Part (c) [1 MARK]


When writing A3, several people reported that the shell prompt appeared before the output of their pf act
process. Why might that occur?

Part (d) [1 MARK]


int main(void) -C
int id = 0;
for (int i = 1; i < 4; i++) {
it (forkO ==! 0) -C
id = i;
Y else •£
print£("Process %d created child %d\n", id, i);
>
>
return 0;
}

In tlie code above, multiple orderiugs of the output (printf statements) can be generated based on how the
operating system schedules processes for execution. How many different orderiugs are possible? You may
assume that all fork and priatf calls succeed.

Part (e) [6 MARKS]


We frequently thiiik of a file system as a tree, with each directory acting as a node in the tree. Write a
program to calculate the number of subdirectories in. the file tree rooted in tlie current working directory
and to prmt the result. For example, if the current directory is empty or contains only normal files, the
program would print O." If the current directory contains two directories, then you' program should
explore both of them. If the first contains one dh'ectory (which itself contains no directories) and the
second confcains no subdirectories, tihen fche progra.m would print "3" ~ calculated by (2 + (1 +0) + (0)).
Your program must use forlcO. Each subdirectory should be explored using a new process. You may
assume that the result will never be larger than 255 (making it safe to send results back to the parent
using an exit status).

You may also assume fchafc fche lielpei' function described above main, which generates au array of the
names of the directories witiuu a given directory, is available and works properly, (If you are unsure how
to use this fimction, write a comment — "// Magic Happened - and then assume that you. have access to
a magic array of strings that contains the directory names in yow current working directory.)

Page 6 of 16 GONT'D. ..
April 2018 Final Examination CSC209H5S

// When this function returns, (*subdirs) will refer to a dynamically allocated array of
// strings. Each element in -the array is the full path to a directory that is contained
// in dir. The function returns the number of strings that have been placed in the
// d.yaafliically allocated array pointed to by subdirs,
int gQ-t;^subdirjaames(chaD: *dir, char ***subdirs) ;

// Other helper prototypes (not required):

int main(void) -C

Page 7 of 16 CONT'D. ..
April 2018 Final Examination CSC209H5S

Question 4. File Descriptors [6 MARKS]

Part (a) [2 MARKS]


Consider fche code below, that coutams some iU-advlsed statemen.ts:

iat fds [21;


pipe(fds);
if (forkQ > 0) {
fds[03 = 0; // Yuckl Assigning 0 to the read end.
>

(a) Can the parent and child still communicate through the pipe, with the parent writing and cluld reading?
Briefly justify your aJafiwer.

(b) If the child exits while the parent is writing data to the pipe, will the parent Imow that the child has
exited? Briefly justify your answer.

Part (b) [4 MARKS]


For each of the statements below, provide one explanation of what would cause the foeliavionr described in
the comments in each box. Please be as precise as possible.

result = read(fd, but, SIZE);


// process blocks

result =» read(£d, buf, SIZE);


// result !=a: 0

result = read(£d, buf, SIZE);


// result < SIZE but !" 0

result = write(£d» buf, SIZE);


// process blocks

Page 9 of 16 CONT'D.
April 2018 Final Examination CSC209H5S

Question 5. Signals (5 MARKS]

Part (a) [1 MARK]


Some signals, like SIGIKT are maskable by the users while otliers, Ulce SIGKILL are uofc. Wliy?

Part (b) [4 MARKS]


Write a program that prints Stop poking me/ to STDOUT and then sleeps for 5 seconds whenever the
user sends a SIGZKT signal. While the program is sleeping, it should not immediately respond to a.notlier
SIGINT. When it is not sleeping, the program just loops (see the bottom of the page).

while (1);
return 0;
}

Page 10 of 16 CONT'D.
April 2018 Final Examination CSC209H5S

Question 6. Sockets and Select [8 MARKS]

Part (a) [1 MARK]


Why is both an address and a port reqmred to connect fco a server?

Part (b) [1 MARK]


Why does tkere ueed to be a, "network order" for iutegers and a "network newlme" ?

Page 11 of 16 CONT'D. ..
April 2018 Final Examination CSC209H5S

Part (c) [4 MARKS]


Assume that au fd-set named alljfds, cou^aming file descriptors to listen to, ajid au int named raax-fd,
confcainmg the value of the la-rgesfc file descripfcor, have been defined and initialized. Write code, below,
that uses select to print (to STDQUT) text that is sent on any of the descriptors. Your code does not
need to create new comiectioms or to remove closed comiecfcions. It also does not need to remove network
newlineS) but it should not priut garbage.

// fcLset alUds
// i&t max_fd =
while (1) {

Page 12 of 16 CONT'D. ..
April 2018 Final Examination CSC209H5S

Part (d) [2 MARKS]


Assume that an fcLset named allJFds, contauiiug file descriptors to listen to, and aa int named max-fd,
containing the value of the largest file descriptor, have been defined and inifcialized. Write code to add a
new file descriptor, stored in new-fd, to the set, and to remove the file descriptor, stored in oldJ'd, from
the set.

Total Marks = 40

Page 13 of 16 CONT>D. ..
April 2018 Final Examination CSC209H8S

C function prototypes and structs:

lnt acceptdat sock, struct sockaddr *addr, int ^addrlen)


char ^asctimeCconst struct tm *timeptr)
int bind(int sock, struct sockaddr *addr, int; addrlen)
infc close(int £d)
int closedir(DIR *dir)
int comiect(int sock, stznct sockaddr ^addr, int addrlen)
char *ctime(const tim9_t * clock); int dup2(in1; oldfd, int newfd)
int execl(const char *patli, const char *arg0, ... /+, (char *)0 */);
int execvp(const char *file^ char *argvf])
int fclose(FILE ^stream)
i&t FD_ISSET(int fd, fd-set *fds)
void FDJSETCint fd, fd^set *fds)
void FD-CLRdnt £d, £d»set *fds)
void FD-ZEROCfd-set *fds)
char *fgets(char *s, int n, FILE ^stream)
int fileno(FILE *stream)
picLt fork(void)
FILE *fopen(const char *file, coast char +mode)
int fprintf(FILE * restrict stream, const char * res'brict format, ...);
sizejfc 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);
picLt getpid(void);
picLt ge-tppid(void);
unsigned long iat 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 kilKint pid, int signo)
int llsten(int sock, int n)
void *malloc<.size_t size);
unsigned long i&t ntohl(unsigned long int netlong)
unsigned short int ntohs(unsign.ed short int netshort)
iat opea(const char *path, int oflag)
/* oflag is CLWRONLY I O^GREAT for write and OJtDONLY for read */
DIR *opendir(const char fname)
int pclose(FILE *streaia)
int pipe(int filedes[2])
FILE *popen(char *cmds1;r, char *mode)
ssize-t read(int d» void *buf, size^t nbytes);
s'bmct dit-ent *r6addi2"(DIR *dir)
int selectdn-t maxfdpl, fd-set *readfds, fd-set *write£ds, fd-set *excep'fcfds, s-fcruct timoval *fclffieout;)
int slgactiondnt slgnura, const; struct Bigaction *act, s-truct sigaction *o3.dact)
/* actions include SIG_DFL and SIG^IGN */
int sigaddset(sigset_t *set, iat signum)
int sigemptyset(sigset_t *set)
int sigprocmask(int ILOW, const sigset^t *set, sigset^t ^oldset)
/*how has the value SIG_BLOCK» SIG^NBLOCK, or SIG-SETHASK */
unslgned int sleep(unsigned int secondB)
int socket(int family, int type, int protocol) /* fajs[iily=PF-INET, type=SOCK-STREAM, protocol=0 */
int sprintf(char !t«s, const char ^format, ...)
int stat(const char !(:filejiame, struct stat *buf)

Page 15 of 16 END OF FINAL EXAMINATION


April 2018 Final Examination CSC209H5S

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 *slj consl; char *s2» size-t a)
char *st3:ncpy(char *dest, const char :«src, size^t n)
long strtol(const char ^restrict str, char **restrict endptr, int base);
int waitdnt ^status)
int waitpiddnt pid, int *stat, int options) /* options = 0 or WKOHANG*/
ssizejk write(int d^ const void *buf, size-t nbytes);

Useful macros

WIFEXITED(status) WEXITSTATUS(status) FD-ZERO(fd-set)


yiFSIGNALED(status) WTERMSIG(status) PD-SET(fd, fcLset)
WIFSTOPPED(status) WSTDPSIG(status) FDJJNSET(fd, fd-set)

Useful structs
struct sigaction {
void (^saJiaadler)(int);
struct stat {
sigset-t sa-mask;
dev-t st_dev; /* ID of device containing file */
int sajElags;
inorb st-lno; /* inode number */
} mode-t stjnode; /* protection */
s{;ruct liosteat {
nlink-t; st-nlink; /* number of hard linlcs */
char *Ii_naiae; // name of host
uid-t st-.uid; /* user ID o£ owner */
char **h-aliases; // alias list
gicLt st-gid; /* group ID of owner */
int h-addrtype; // liost address type
dev-t st-rdev; /* dsvice ID (if special file) */
int hJ.ength; // length of address
off-t st_sizei /* total size, in bytes */
char *h-addr; // address
blksize-t st-blksize; /* blocksize for file system I/O */
} blkcnt-t stjslocks; /* aumber of 512B blocks allocated */
struct sockaddrJLn {
time_t st-atime; /* time of last access */
sa-family-t sin-Eamily;
time-t st-mtime; /* time of last modification */
unsigaed sliort Int sin^port;
time-t st-ctime; /* time of last status change */
struct in-addr sin-addr;
unsigned char pad[8]; /^Unused*/
};
}
Shell comparison operators

Shell Description
-d filename Exists as a directory
"£ filename Exists as a regular file.
Useful Makefile variables
-r filename Exists as a readable file
-w filename Exists as a writable file.
$0 target
~x filename Exists as an executable file.
$" list of prerequisites
-z string True if empty string ~w first prerequisite
stri = str2 True if strl equals s'fcr2
$? return code of last program executed
strl t= str2 True if strl not equal to s-fcr2
intl -eq int2 True if intl equals int2
-ne, -gfc, -It, -Ie For nmcbsrs
!a, >, >=, <, <° For strings
-a, -o And, or.

Page 16 of 16 END OF FINAL EXAMINATION

You might also like