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

Size: px
Start display at page:

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

Transcription

1 CSC B09H1 S 2017 Final exam Duration 150 minutes Aids allowed: Handwritten single-sided crib sheet Last Name: Student Number: Lab day, time: First Name: Instructor: Bianca Schroeder Do not turn this page until you have received the signal to start. (Please fill out the identification section above and read the instructions below.) Good Luck! # 1: / 6 # 2: / 9 This midterm consists of 7 questions on 30 pages (including this one). When you receive the signal to start, please make sure that your copy is complete. Comments are not required except where indicated, although they may help us mark your answers. Note, that on the last pages of the exam we are providing some information from various Unix man pages that might be useful. If you use any space for rough work, indicate clearly what you want marked. # 3: / 9 # 4: / 8 # 5: / 9 # 6: / 9 # 7: / 7 TOTAL: /57 Total Pages = 30 Page 1 cont d...

2 Question 1. [6 marks] Some of the code fragments below have a problem. For each fragment indicate whether the code works as intended or whether there is an error (logical error, compile-time error/warning, or runtime error). Assume all programs are compiled using the C99 standard. For this question, we ll assume programs which do not terminate are errors as well. If there is an error in a fragment, explain briefly what is wrong in the box. We have intentionally omited the error checking of the system calls to simplify the examples. Do not report this as an error. Part (a) [1 mark] int x = 5; // checking whether x equals 6 if ( x = 6 ) { printf("x equals 6\n"); } Works as intended Error Part (b) [1 mark] int x; //reading a value for x scanf("%d", &x); Works as intended Error Page 2 of 30 cont d...

3 Part (c) [1 mark] struct student { int age; char *name; } // Increase the age of a student by amt. void increase_age(struct student s, int amt) { s.age += amt; } int main() { struct student rob; rob.age = 10; increase_age(rob, 5); printf("%d should be 15\n", rob.age); } Works as intended Error Part (d) [1 mark] char * st = malloc(31); // reading a string into st // you may assume that not more than 30 characters are read scanf("%s", &st); Works as intended Error Page 3 of 30 cont d...

4 Part (e) [1 mark] #include <string.h> int main() { char * st; // copying "abc" into st strcpy(st, "abc"); return 0; } Works as intended Error Part (f) [1 mark] char st1[] = "abc"; char st2[] = "abc"; if ( st1 == st2 ) printf("strings are identical"); else printf("not identical"); Works as intended Error Page 4 of 30 cont d...

5 Question 2. [9 marks] In this question you will write a function hash that will take as arguments the name of a file filename and a hash block size blocksize. It will then read the contents of file filename byte by byte and compute (and return) a hash with the size specified in blocksize. The hash you implement should be based on xor and your function should be able to handle text files as well as binary files. You can assume that blocksize passed to the function is a valid block size and that no error occur during any of the system calls you might make. You can also assume that any libraries you need have been included. char *hash(char *filename, int blocksize) { } Page 5 of 30 cont d...

6 Question 3. [9 marks] Suppose you want write a program with two processes that communicate through a pipe. Decide for each of the following statements whether they are correct or not: You need to call pipe() before you call fork(). True False You need to call fork() before you call pipe(). True False You need to call pipe, but you don t necessarily have to call fork. True False Pipes are uni-directional, which means that only the parent can read and only the child can write. True False It is important to close the unused end of a pipe because otherwise the read end of the pipe will block STDIN. True False It is important to close the unused end of a pipe because otherwise the tobacco will spill out of the pipe ends left open. True False A read call will block if the pipe is empty. True False A write call will block if the pipe is full. True False A child inherits all the open file descriptors from the parent, including those corresponding to pipes. True False Page 6 of 30 cont d...

7 Question 4. [8 marks] Consider the following makefile: FLAGS = -Wall -std=gnu99 DEPENDENCIES = hash.h ftree.h all: fcopy fcopy: fcopy.o ftree.o hash_functions.o gcc ${FLAGS} -o $@ $^ %.o: %.c ${DEPENDENCIES} gcc ${FLAGS} -c $< clean: rm *.o fcopy Assume the directory that contains the makefile contains the following files (and no others): hash.h ftree.h ftree.c fcopy.c hash functions.c. Suppose the following commands are run one after the other. Fill in the table to show what files are created, deleted or modified as a result of running each command. If no files are created, deleted or modified after a particular command, write NO CHANGE. Command Names of files created or changed Names of files deleted make ftree.o make fcopy rm ftree.o make all Page 7 of 30 cont d...

8 Question 5. [9 marks] Consider the program below and assume that it runs without encountering any errors. #include <stdio.h> #include <signal.h> #include <unistd.h> void brain_pain(int signal) { printf("my brain is hurting!\n"); printf("so much!\n"); } int main() { } printf("the final:\n"); struct sigaction sa; sa.sa_handler = brain_pain; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); // sigaddset(&sigset, SIGTERM); // STATEMENT A sigaction(sigint, &sa, NULL); printf("i can t wait...\n"); kill(getpid(), SIGINT); printf("...until it s over.\n"); exit(0); Part (a) [3 marks] Assuming that the program does not encounter any errors and does not receive any signals besides the ones it is sending itself. Decide for each of the following output sequences whether they could have been generated by the program. The final: I can t wait... My brain is hurting! So much!...until it s over. The final: I can t wait... My brain is hurting! Possible Not Possible Possible Not Possible Page 8 of 30 cont d...

9 The final: I can t wait......until it s over. The final: I can t wait... My brain is hurting! So much! Possible Not Possible Possible Not Possible Part (b) [3 marks] Now assume while the program is running the user sends a SIGTERM signal from the command line (e.g. using the kill command) at a random point during the execution. Which of the following outputs are possible? The final: The final: I can t wait... I can t wait... My brain is hurting! My brain is hurting! So much!...until it s over. Possible Not Possible Possible Not Possible The final: I can t wait......until it s over. The final: I can t wait... My brain is hurting! So much! Possible Not Possible Possible Not Possible Part (c) [3 marks] Now assume that we uncomment STATEMENT A (i.e. we remove the comment signs at the beginning of the line) and recompile. Then again while the program is running the user sends a SIGTERM signal from the command line (e.g. using the kill command) at a random point during the execution. Which of the following outputs are possible? The final: I can t wait... My brain is hurting! So much!...until it s over. The final: I can t wait... My brain is hurting! Possible Not Possible Possible Not Possible The final: I can t wait......until it s over. The final: I can t wait... My brain is hurting! So much! Possible Not Possible Possible Not Possible Page 9 of 30 cont d...

10 Question 6. [9 marks] The (incomplete) function echo below is part of a server program that serves as the middleman between two clients that want to communicate, while remaining anonymous to each other. The server first establishes a connection (using sockets) with each of the two clients, and then echos data back and forth between the clients, i.e. it takes any data it reads from the first client and forwards it to the second client, and vice versa. The echo function is a helper function used by the server program, after it has established the two connections with the clients. The function takes the file descriptors for the two client connections as arguments and implements the echoing of data between the two clients. The function should never block on a read and should not make any assumptions about the order in which the clients write data. It should keep running until one of the two clients closes their side of the connection. Complete the function below. You can assume that no errors occur in any system calls you might make and omit error handling. #define MAX_SIZE 128 void echo (int fd1, int fd2) { char buf[max_size]; Page 10 of 30 cont d...

11 Page 11 of 30 cont d...

12 Question 7. [7 marks] The program below expects as command line arguments an IP address and a port number, then establishes a connection to a server at that IP address and port, reads a message from the server and writes it to standard output. You can assume that all the proper libraries have been included. Unfortunately, the programmer made 7 mistakes when writing this program, which can lead to either compile-time errors/warnings or runtime errors. 0 #define MAX_SIZE int main(int argc, char **argv) { 3 char *buf; 4 5 // create the socket 6 int soc = socket(af_inet, 0); 7 if (soc < 0) { 8 perror("socket"); 9 exit(1); 10 } // set up the sockaddr_in struct for connecting 13 struct sockaddr_in peer; 14 peer.sin_port = htons(argv[2]); 15 if (inet_pton(af_inet, argv[1], peer.sin_addr) < 1) { 16 perror("inet_pton"); 17 close(soc); 18 exit(1); 19 } // connect the socket 22 if (connect(soc, (struct sockaddr *)&peer, 0) < -1) { 23 perror("connect"); 24 close(soc); 25 exit(1); 26 } read(soc, buf, sizeof(buf)); 29 write(stdout_fileno, buf, MAX_SIZE); } Identify the mistakes and, on the next two pages, state for each mistake which line of the program is affected, and explain briefly what the mistake is. You can list the errors in any order. Page 12 of 30 cont d...

13 Part (a) Error 1: [2 marks] Part (b) Error 2: [2 marks] Part (c) Error 3: [2 marks] Page 13 of 30 cont d...

14 Part (d) Error 4: [2 marks] Part (e) Error 5: [2 marks] Part (f) Error 6: [2 marks] Part (g) Error 7: [2 marks] Page 14 of 30 cont d...

15 (Extra space, if needed) Page 15 of 30 cont d...

16 (Extra space, if needed) Page 16 of 30 cont d...

17 Appendix Useful structs struct sockaddr in { sa family t sin family; unsigned short int sin port; struct in addr sin addr; unsigned char pad[8]; /*Unused*/ } Man page for sigemptyset, sigfillset, sigaddset, sigdelset, sigismember #include <signal.h> int sigemptyset(sigset_t *set); int sigfillset(sigset_t *set); int sigaddset(sigset_t *set, int signum); int sigdelset(sigset_t *set, int signum); int sigismember(const sigset_t *set, int signum); These functions allow the manipulation of POSIX signal sets. sigemptyset() initializes the signal set given by set to empty, with all signals excluded from the set. sigfillset() initializes set to full, including all signals. sigaddset() and sigdelset() add and delete respectively signal signum from set. sigismember() tests whether signum is a member of set. Objects of type sigset t must be initialized by a call to either sigemptyset() or sigfillset() before being passed to the functions sigaddset(), sigdelset() and sigismember() or the additional glibc functions described below (sigisemptyset(), sigandset(), and sigorset()). The results are undefined if this is not done. RETURN VALUE sigemptyset(), sigfillset(), sigaddset(), and sigdelset() return 0 on success and -1 on error. sigismember() returns 1 if signum is a member of set, 0 if signum is not a member, and -1 on error. Page 17 of 30 cont d...

18 Man page for sigaction #include <signal.h> int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact); DESCRIPTION The sigaction() system call is used to change the action taken by a process on receipt of a specific signal. (See signal(7) for an overview of signals.) signum specifies the signal and can be any valid signal except SIGKILL and SIGSTOP. If act is non-null, the new action for signal signum is installed from act. If oldact is non-null, the previous action is saved in oldact. The sigaction structure is defined as something like: struct sigaction { void (*sa_handler)(int); sigset_t sa_mask; int sa_flags; }; sa handler specifies the action to be associated with signum and may be SIG DFL for the default action, SIG IGN to ignore this signal, or a pointer to a signal handling function. This function receives the signal number as its only argument. sa mask specifies a mask of signals which should be blocked (i.e., added to the signal mask of the thread in which the signal handler is invoked) during execution of the signal handler. In addition, the signal which triggered the handler will be blocked, unless the SA NODEFER flag is used. sa flags specifies a set of flags which modify the behavior of the signal. RETURN VALUE sigaction() returns 0 on success and -1 on error. Page 18 of 30 cont d...

19 Man page for select, FD CLR, FD ISSET, FD SET, FD ZERO - synchronous I/O multiplexing #include <sys/select.h> int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); void FD_CLR(int fd, fd_set *set); int FD_ISSET(int fd, fd_set *set); void FD_SET(int fd, fd_set *set); void FD_ZERO(fd_set *set); select() allows a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become ready for some class of I/O operation (e.g., input possible). A file descriptor is considered ready if it is possible to perform the corresponding I/O operation (e.g., read(2)) without blocking. Three independent sets of file descriptors are watched. Those listed in readfds will be watched to see if characters become available for reading (more precisely, to see if a read will not block; in particular, a file descriptor is also ready on end-of-file), those in writefds will be watched to see if a write will not block, and those in exceptfds will be watched for exceptions. On exit, the sets are modified in place to indicate which file descriptors actually changed status. Each of the three file descriptor sets may be specified as NULL if no file descriptors are to be watched for the corresponding class of events. Four macros are provided to manipulate the sets. FD ZERO() clears a set. FD SET() and FD CLR() respectively add and remove a given file descriptor from a set. FD ISSET() tests to see if a file descriptor is part of the set; this is useful after select() returns. nfds is the highest-numbered file descriptor in any of the three sets, plus 1. The timeout argument specifies the minimum interval that select() should block waiting for a file descriptor to become ready. (This interval will be rounded up to the system clock granularity, and kernel scheduling delays mean that the blocking interval may overrun by a small amount.) If both fields of the timeval structure are zero, then select() returns immediately. (This is useful for polling.) If timeout is NULL (no timeout), select() can block indefinitely. RETURN VALUE On success, select() returns the number of file descriptors contained in the three returned descriptor sets (that is, the total number of bits that are set in readfds, writefds, exceptfds) which may be zero if the timeout expires before anything interesting happens. On error, -1 is returned, and errno is set appropriately; the sets and timeout become undefined, so do not rely on their contents after an error. Page 19 of 30 cont d...

20 Man page for socket #include <sys/types.h> /* See NOTES */ #include <sys/socket.h> int socket(int domain, int type, int protocol); DESCRIPTION socket() creates an endpoint for communication and returns a descriptor. The domain argument specifies a communication domain; this selects the protocol family which will be used for communication. These families are defined in sys/socket.h. The currently understood formats include: Name Purpose Man page AF UNIX, AF LOCAL Local communication unix(7) AF INET IPv4 Internet protocols ip(7) AF INET6 IPv6 Internet protocols ipv6(7) AF IPX IPX - Novell protocols The socket has the indicated type, which specifies the communication semantics. Currently defined types are: SOCK STREAM Provides sequenced, reliable, two-way, connection-based byte streams. An out-of-band data transmission mechanism may be supported. SOCK DGRAM Supports datagrams (connectionless, unreliable messages of a fixed maximum length). SOCK RAW Provides raw network protocol access. The protocol specifies a particular protocol to be used with the socket. Normally only a single protocol exists to support a particular socket type within a given protocol family, in which case protocol can be specified as 0. However, it is possible that many protocols may exist, in which case a particular protocol must be specified in this manner. The protocol number to use is specific to the communication domain in which communication is to take place; see protocols(5). See getprotoent(3) on how to map protocol name strings to protocol numbers. Sockets of type SOCK STREAM are full-duplex byte streams, similar to pipes. They do not preserve record boundaries. A stream socket must be in a connected state before any data may be sent or received on it. A connection to another socket is created with a connect(2) call. Once connected, data may be transferred using read(2) and write(2) calls or some variant of the send(2) and recv(2) calls. When a session has been completed a close(2) may be performed. Out-of-band data may also be transmitted as described in send(2) and received as described in recv(2). The communications protocols which implement a SOCK STREAM ensure that data is not lost or duplicated. If a piece of data for which the peer protocol has buffer space cannot be successfully transmitted within a reasonable length of time, then the connection is considered to be dead. When SO KEEPALIVE is enabled on the socket the protocol checks in a protocol-specific manner if the other end is still alive. A SIGPIPE signal is raised if a process sends or receives on a broken stream; this causes naive processes, which do not handle the signal, to exit. SOCK SEQPACKET sockets employ the same system calls as SOCK STREAM sockets. The only difference is that read(2) calls will return only the amount of data requested, and any data remaining in the arriving packet will be discarded. Also all message boundaries in incoming datagrams are preserved. RETURN VALUE On success, a file descriptor for the new socket is returned. appropriately. On error, -1 is returned, and errno is set Page 20 of 30 cont d...

21 Man page for connect and inet pton #include <sys/types.h> /* See NOTES */ #include <sys/socket.h> int connect(int sockfd, const struct sockaddr *addr, addrlen); socklen_t DESCRIPTION The connect() system call connects the socket referred to by the file descriptor sockfd to the address specified by addr. The addrlen argument specifies the size of addr. The format of the address in addr is determined by the address space of the socket sockfd; see socket(2) for further details. If the socket sockfd is of type SOCK DGRAM then addr is the address to which datagrams are sent by default, and the only address from which datagrams are received. If the socket is of type SOCK STREAM or SOCK SEQPACKET, this call attempts to make a connection to the socket that is bound to the address specified by addr. Generally, connection-based protocol sockets may successfully connect() only once; connectionless protocol sockets may use connect() multiple times to change their association. Connectionless sockets may dissolve the association by connecting to an address with the sa family member of sockaddr set to AF UNSPEC (supported on Linux since kernel 2.2). RETURN VALUE If the connection or binding succeeds, zero is returned. On error, -1 is returned, and errno is set appropriately. #include <arpa/inet.h> int inet_pton(int af, const char *src, void *dst); DESCRIPTION This function converts the character string src into a network address structure in the af address family, then copies the network address structure to dst. The af argument must be either AF INET or AF INET6. inet pton() returns 1 on success (network address was successfully converted). 0 is returned if src does not contain a character string representing a valid network address in the specified address family. If af does not contain a valid address family, -1 is returned and errno is set to EAFNOSUPPORT. Page 21 of 30 cont d...

22 Man page for htonl, htons, ntohl, ntohs #include <arpa/inet.h> uint32_t htonl(uint32_t hostlong); uint16_t htons(uint16_t hostshort); uint32_t ntohl(uint32_t netlong); uint16_t ntohs(uint16_t netshort); DESCRIPTION The htonl() function converts the unsigned integer hostlong from host byte order to network byte order. The htons() function converts the unsigned short integer hostshort from host byte order to network byte order. The ntohl() function converts the unsigned integer netlong from network byte order to host byte order. The ntohs() function converts the unsigned short integer netshort from network byte order to host byte order. On the i386 the host byte order is Least Significant Byte first, whereas the network byte order, as used on the Internet, is Most Significant Byte first. Page 22 of 30 cont d...

23 Man page for fread #include <stdio.h> size_t fread(void *ptr, size_t size, size_t nmembfile *" stream ); size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream); DESCRIPTION The function fread() reads nmemb elements of data, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr. The function fwrite() writes nmemb elements of data, each size bytes long, to the stream pointed to by stream, obtaining them from the location given by ptr. RETURN VALUE On success, fread() and fwrite() return the number of items read or written. This number equals the number of bytes transferred only when size is 1. If an error occurs, or the end of the file is reached, the return value is a short item count (or zero). fread() does not distinguish between end-of-file and error, and callers must use feof(3) and ferror(3) to determine which occurred. Man page for read #include <unistd.h> ssize_t read(int fd, void *buf, size_t count); DESCRIPTION read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf. On files that support seeking, the read operation commences at the current file offset, and the file offset is incremented by the number of bytes read. If the current file offset is at or past the end of file, no bytes are read, and read() returns zero. If count is zero, read() may detect the errors described below. In the absence of any errors, or if read() does not check for errors, a read() with a count of 0 returns zero and has no other effects. If count is greater than SSIZE MAX, the result is unspecified. RETURN VALUE On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal. On error, -1 is returned, and errno is set appropriately. In this case it is left unspecified whether the file position (if any) changes. Page 23 of 30 cont d...

24 Man page for write #include <unistd.h> ssize_t write(int fd, const void *buf, size_t count); DESCRIPTION write() writes up to count bytes from the buffer pointed buf to the file referred to by the file descriptor fd. The number of bytes written may be less than count if, for example, there is insufficient space on the underlying physical medium, or the RLIMIT FSIZE resource limit is encountered (see setrlimit(2)), or the call was interrupted by a signal handler after having written less than count bytes. (See also pipe(7).) For a seekable file (i.e., one to which lseek(2) may be applied, for example, a regular file) writing takes place at the current file offset, and the file offset is incremented by the number of bytes actually written. If the file was open(2)ed with O APPEND, the file offset is first set to the end of the file before writing. The adjustment of the file offset and the write operation are performed as an atomic step. POSIX requires that a read(2) which can be proved to occur after a write() has returned returns the new data. Note that not all file systems are POSIX conforming. RETURN VALUE On success, the number of bytes written is returned (zero indicates nothing was written). On error, -1 is returned, and errno is set appropriately. If count is zero and fd refers to a regular file, then write() may return a failure status if one of the errors below is detected. If no errors are detected, 0 will be returned without causing any other effect. If count is zero and fd refers to a file other than a regular file, the results are not specified. Page 24 of 30 cont d...

25 Man page for strcpy and strncpy #include <string.h> char *strcpy(char *dest, const char *src); char *strncpy(char *dest, const char *src, size_t n); DESCRIPTION The strcpy() function copies the string pointed to by src, including the terminating null byte, to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy. The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null terminated. If the length of src is less than n, strncpy() pads the remainder of dest with null bytes. RETURN VALUE The strcpy() and strncpy() functions return a pointer to the destination string dest. Man page for strlen DESCRIPTION RETURN VALUE #include <string.h> size_t strlen(const char *s); The strlen() function calculates the length of the string s, excluding the terminating null byte. The strlen() function returns the number of bytes in the string s. Page 25 of 30 cont d...

26 Man page for fopen DESCRIPTION RETURN VALUE #include <stdio.h> FILE *fopen(const char *path, const char *mode); The fopen() function opens the file whose name is the string pointed to by path and associates a stream with it. The argument mode points to a string beginning with one of the following sequences (possibly followed by additional characters, as described below): r Open text file for reading. The stream is positioned at the beginning of the file. r+ Open for reading and writing. The stream is positioned at the beginning of the file. w Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file. Upon successful completion fopen() returns a FILE pointer. Otherwise, NULL is returned and errno is set to indicate the error. Page 26 of 30 cont d...

27 Man page for fork DESCRIPTION RETURN VALUE #include <unistd.h> pid_t fork(void); fork() creates a new process by duplicating the calling process. The new process, referred to as the child, is an exact duplicate of the calling process, referred to as the parent, except for the following points: * The child has its own unique process ID, and this PID does not match the ID of any existing process group (setpgid(2)). * The child s parent process ID is the same as the parent s process ID. On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately. Man page for execl DESCRIPTION RETURN VALUE #include <unistd.h> int execl(const char *path, const char *arg,...); The exec() family of functions replaces the current process image with a new process image. The initial argument for these functions is the name of a file that is to be executed. The const char *arg and subsequent ellipses in the execl() function can be thought of as arg0, arg1,..., argn. Together they describe a list of one or more pointers to null-terminated strings that represent the argument list available to the executed program. The first argument, by convention, should point to the filename associated with the file being executed. The list of arguments must be terminated by a NULL pointer, and, since these are variadic functions, this pointer must be cast (char *) NULL. The exec() functions only return if an error has occurred. The return value is -1, and errno is set to indicate the error. Page 27 of 30 cont d...

28 Man page for scanf #include <stdio.h> int scanf(const char *format,...); int fscanf(file *stream, const char *format,...); DESCRIPTION The scanf() family of functions scans input according to format as described below. This format may contain conversion specifications; the results from such conversions, if any, are stored in the locations pointed to by the pointer arguments that follow format. Each pointer argument must be of a type that is appropriate for the value returned by the corresponding conversion specification. If the number of conversion specifications in format exceeds the number of pointer arguments, the results are undefined. If the number of pointer arguments exceeds the number of conversion specifications, then the excess pointer arguments are evaluated, but are otherwise ignored. The scanf() function reads input from the standard input stream stdin, fscanf() reads input from the stream pointer stream, and sscanf() reads its input from the character string pointed to by str. The format string consists of a sequence of directives which describe how to process the sequence of input characters. If processing of a directive fails, no further input is read, and scanf() returns. A failure can be either of the following: input failure, meaning that input characters were unavailable, or matching failure, meaning that the input was inappropriate. Man page for malloc DESCRIPTION RETURN VALUE #include <stdlib.h> void *malloc(size_t size); The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free(). The malloc() function return a pointer to the allocated memory that is suitably aligned for any kind of variable. On error, these functions return NULL. NULL may also be returned by a successful call to malloc() with a size of zero, or by a successful call to calloc() with nmemb or size equal to zero. Page 28 of 30 cont d...

29 From the man page on signals Each signal has a current disposition, which determines how the process behaves when it is delivered the signal. The entries in the Action column of the tables below specify the default disposition for each signal, as follows: Term Ign Core Stop Cont Default action is to terminate the process. Default action is to ignore the signal. Default action is to terminate the process and dump core (see core(5)). Default action is to stop the process. Default action is to continue the process if it is currently stopped. Linux supports the standard signals listed below. Several signal numbers are architecture-dependent, as indicated in the Value column. (Where three values are given, the first one is usually valid for alpha and sparc, the middle one for x86, arm, and most other architectures, and the last one for mips. (Values for parisc are not shown; see the Linux kernel source for signal numbering on that architecture.) A dash (-) denotes that a signal is absent on the corresponding architecture. First the signals described in the original POSIX standard. Signal Value Action Comment SIGHUP 1 Term Hangup detected on controlling terminal or death of controlling process SIGINT 2 Term Interrupt from keyboard SIGQUIT 3 Core Quit from keyboard SIGILL 4 Core Illegal Instruction SIGABRT 6 Core Abort signal from abort(3) SIGFPE 8 Core Floating-point exception SIGKILL 9 Term Kill signal SIGSEGV 11 Core Invalid memory reference SIGPIPE 13 Term Broken pipe: write to pipe with no readers; see pipe(7) SIGALRM 14 Term Timer signal from alarm(2) SIGTERM 15 Term Termination signal SIGUSR1 30,10,16 Term User-defined signal 1 SIGUSR2 31,12,17 Term User-defined signal 2 SIGCHLD 20,17,18 Ign Child stopped or terminated SIGCONT 19,18,25 Cont Continue if stopped SIGSTOP 17,19,23 Stop Stop process Page 29 of 30 cont d...

30 SIGTSTP 18,20,24 Stop Stop typed at terminal SIGTTIN 21,21,26 Stop Terminal input for background process SIGTTOU 22,22,27 Stop Terminal output for background process The signals SIGKILL and SIGSTOP cannot be caught, blocked, or ignored. Page 30 of 30 End of Examination

Lesson 3. The func procedure allows a user to choose the action upon receipt of a signal.

Lesson 3. The func procedure allows a user to choose the action upon receipt of a signal. Lesson 3 Signals: When a process terminates abnormally, it usually tries to send a signal indicating what went wrong. C programs can trap these for diagnostics. Software interrupts: Stop executing the

More information

15-213/ Final Exam Notes Sheet Spring 2013!

15-213/ Final Exam Notes Sheet Spring 2013! Jumps 15-213/18-213 Final Exam Notes Sheet Spring 2013 Arithmetic Operations Jump Condi+on jmp 1 je ZF jne ~ZF js SF jns ~SF jg ~(SF^OF)&~ZF jge ~(SF^OF) jl (SF^OF) jle (SF^OF) ZF ja ~CF&~ZF jb CF Format

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. (Advanced Control Signals)

CSci 4061 Introduction to Operating Systems. (Advanced Control Signals) CSci 4061 Introduction to Operating Systems (Advanced Control Signals) What is a Signal? Signals are a form of asynchronous IPC Earlier: Non-blocking I/O and check if it has happened => polling Problem

More information

Signals. CSC209: Software Tools and Systems Programming. Furkan Alaca & Paul Vrbik

Signals. CSC209: Software Tools and Systems Programming. Furkan Alaca & Paul Vrbik Signals CSC209: Software Tools and Systems Programming Furkan Alaca & Paul Vrbik University of Toronto Mississauga https://mcs.utm.utoronto.ca/~209/ Week 9 Acknowledgement These slides are built upon material

More information

// socket for establishing connections

// socket for establishing connections #include #include #include #include #include #include #include #define FILELENGTH 511 // This is not right #define

More information

System Programming. Signals I

System Programming. Signals I 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 Signals

More information

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

Student Number: Instructor: Reid Section: L5101 (6:10-7:00pm) Final Test Duration 50 minutes Aids allowed: none Last Name: Student Number: First Name: Instructor: Reid Section: L5101 (6:10-7:00pm) Do not turn this page until you have received the signal to start.

More information

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

Student Number: Instructor: Reid Section: L0101 (10:10-11:00am) Midterm Test Duration 50 minutes Aids allowed: none Last Name: Student Number: First Name: Instructor: Reid Section: L0101 (10:10-11:00am) Do not turn this page until you have received the signal to start.

More information

CSC209H Lecture 10. Dan Zingaro. March 18, 2015

CSC209H Lecture 10. Dan Zingaro. March 18, 2015 CSC209H Lecture 10 Dan Zingaro March 18, 2015 Creating a Client To create a client that can connect to a server, call the following, in order: socket: create a communication endpoint This is the same as

More information

Process management. What s in a process? What is a process? The OS s process namespace. A process s address space (idealized)

Process management. What s in a process? What is a process? The OS s process namespace. A process s address space (idealized) Process management CSE 451: Operating Systems Spring 2012 Module 4 Processes Ed Lazowska lazowska@cs.washington.edu Allen Center 570 This module begins a series of topics on processes, threads, and synchronization

More information

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

Good Luck! Marking Guide. APRIL 2014 Final Exam CSC 209H5S APRIL 2014 Final Exam CSC 209H5S Last Name: Student #: First Name: Signature: UNIVERSITY OF TORONTO MISSISSAUGA APRIL 2014 FINAL EXAMINATION CSC209H5S System Programming Daniel Zingaro Duration - 3 hours

More information

CSE 451: Operating Systems Winter Module 4 Processes. Mark Zbikowski Allen Center 476

CSE 451: Operating Systems Winter Module 4 Processes. Mark Zbikowski Allen Center 476 CSE 451: Operating Systems Winter 2015 Module 4 Processes Mark Zbikowski mzbik@cs.washington.edu Allen Center 476 2013 Gribble, Lazowska, Levy, Zahorjan Process management This module begins a series of

More information

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 AUGUST 2012 EXAMINATIONS CSC 209H1Y Instructor: Daniel Zingaro Duration three hours PLEASE HAND IN Examination Aids: one two-sided 8.5x11

More information

CSCI 4061: Signals and Signal Handlers

CSCI 4061: Signals and Signal Handlers 1 CSCI 4061: Signals and Signal Handlers Chris Kauffman Last Updated: Thu Oct 19 12:16:40 CDT 2017 2 Logistics Reading Robbins and Robbins Ch 8.1-8.7, 9.1-2 OR Stevens/Rago Ch 10 Goals Sending Signals

More information

Signals. Joseph Cordina

Signals. Joseph Cordina 1 Signals Signals are software interrupts that give us a way to handle asynchronous events. Signals can be received by or sent to any existing process. It provides a flexible way to stop execution of a

More information

Group-A Assignment No. 6

Group-A Assignment No. 6 Group-A Assignment No. 6 R N Oral Total Dated Sign (2) (5) (3) (10) Title : File Transfer using TCP Socket Problem Definition: Use Python for Socket Programming to connect two or more PCs to share a text

More information

CSE 421: Introduction to Operating Systems

CSE 421: Introduction to Operating Systems Recitation 5: UNIX Signals University at Buffalo, the State University of New York October 2, 2013 About Me 4th year PhD student But TA first time From South Korea Today, We will study... What UNIX signals

More information

System Calls and Signals: Communication with the OS. System Call. strace./hello. Kernel. Context Switch

System Calls and Signals: Communication with the OS. System Call. strace./hello. Kernel. Context Switch System Calls and Signals: Communication with the OS Jonathan Misurda jmisurda@cs.pitt.edu System Call An operation (function) that an OS provides for running applications to use CS 1550 2077 strace./hello

More information

Tutorial on Socket Programming

Tutorial on Socket Programming Tutorial on Socket Programming Computer Networks - CSC 458 Department of Computer Science Hao Wang (Slides are mainly from Seyed Hossein Mortazavi, Monia Ghobadi, and Amin Tootoonchian, ) 1 Outline Client-server

More information

Embedded Systems Programming

Embedded Systems Programming Embedded Systems Programming Signaling (Module 24) Yann-Hang Lee Arizona State University yhlee@asuedu (480) 727-7507 Summer 2014 Signals A signal is an event generated by OS in response to some condition

More information

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 AUGUST 2011 EXAMINATIONS CSC 209H1Y Instructor: Daniel Zingaro Duration three hours PLEASE HAND IN Examination Aids: one two-sided 8.5x11

More information

Acontecimentos assíncronos (POSIX signals) Sincronização com múltiplos acontecimentos

Acontecimentos assíncronos (POSIX signals) Sincronização com múltiplos acontecimentos Acontecimentos assíncronos (POSIX signals) Sincronização com múltiplos acontecimentos 1 Rotinas assíncronas POSIX Signals n Condições normais e excepções Signal SIGABRT SIGALRM SIGFPE SIGHUP SIGILL SIGINT

More information

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

Student Number: Instructor: Reid Section: L0201 (12:10-1:00pm) Midterm Test Duration 50 minutes Aids allowed: none Last Name: Student Number: First Name: Instructor: Reid Section: L0201 (12:10-1:00pm) Do not turn this page until you have received the signal to start.

More information

Linux Signals and Daemons

Linux Signals and Daemons Linux and Daemons Alessandro Barenghi Dipartimento di Elettronica, Informazione e Bioingegneria Politecnico di Milano alessandro.barenghi - at - polimi.it April 17, 2015 Recap By now, you should be familiar

More information

Computer Science 330 Operating Systems Siena College Spring Lab 5: Unix Systems Programming Due: 4:00 PM, Wednesday, February 29, 2012

Computer Science 330 Operating Systems Siena College Spring Lab 5: Unix Systems Programming Due: 4:00 PM, Wednesday, February 29, 2012 Computer Science 330 Operating Systems Siena College Spring 2012 Lab 5: Unix Systems Programming Due: 4:00 PM, Wednesday, February 29, 2012 Quote: UNIX system calls, reading about those can be about as

More information

CSE 410: Computer Systems Spring Processes. John Zahorjan Allen Center 534

CSE 410: Computer Systems Spring Processes. John Zahorjan Allen Center 534 CSE 410: Computer Systems Spring 2018 Processes John Zahorjan zahorjan@cs.washington.edu Allen Center 534 1. What is a process? Processes 2. What's the process namespace? 3. How are processes represented

More information

Unix System Programming - Chapter 8

Unix System Programming - Chapter 8 Unix System Programming - Chapter 8 Neal Nelson The Evergreen State College Apr 2010 USP Chapter 8 - Signals Section 8.1 - Basic Signal Concepts Section 8.2 - Generating Signals Section 8.3 - Signal Masks

More information

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

Oral. Total. Dated Sign (2) (5) (3) (2) R N Oral Total Dated Sign (2) (5) (3) (2) Assignment Group- A_07 Problem Definition Write a program using TCP socket for wired network for following Say Hello to Each other ( For all students) File transfer

More information

System Calls & Signals. CS449 Spring 2016

System Calls & Signals. CS449 Spring 2016 System Calls & Signals CS449 Spring 2016 Operating system OS a layer of software interposed between the application program and the hardware Application programs Operating system Processor Main memory

More information

Operating Systems 2010/2011

Operating Systems 2010/2011 Operating Systems 2010/2011 Signals Johan Lukkien 1 Signals A signal is a software generated event notification of state change encapsulation of physical event usually: sent from a process to a process

More information

Interprocess Communication Mechanisms

Interprocess Communication Mechanisms Interprocess Communication 1 Interprocess Communication Mechanisms shared storage These mechanisms have already been covered. examples: shared virtual memory shared files processes must agree on a name

More information

shared storage These mechanisms have already been covered. examples: shared virtual memory message based signals

shared storage These mechanisms have already been covered. examples: shared virtual memory message based signals Interprocess Communication 1 Interprocess Communication Mechanisms shared storage These mechanisms have already been covered. examples: shared virtual memory shared files processes must agree on a name

More information

Overview. POSIX signals. Generation of signals. Handling signals. Some predefined signals. Real-time Systems D0003E 3/3/2009

Overview. POSIX signals. Generation of signals. Handling signals. Some predefined signals. Real-time Systems D0003E 3/3/2009 Overview Real-time Systems D0003E Lecture 13: More on inter-process communication (Burns & Wellings ch. 8, 11 & 10.6) Posix signals Posix timers timers in cygwin (lab environment) event-loop pattern semaphores

More information

Socket Programming for TCP and UDP

Socket Programming for TCP and UDP CSCI4430 Data Communication and Computer Networks Socket Programming for TCP and UDP ZHANG, Mi Jan. 19, 2017 Outline Socket Programming for TCP Introduction What is TCP What is socket TCP socket programming

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

Shell Execution of Programs. Process Groups, Session and Signals 1

Shell Execution of Programs. Process Groups, Session and Signals 1 Shell Execution of Programs Process Groups, Session and Signals 1 Signal Concepts Signals are a way for a process to be notified of asynchronous events (software interrupts). Some examples: a timer you

More information

CSC209 Review. Yeah! We made it!

CSC209 Review. Yeah! We made it! CSC209 Review Yeah! We made it! 1 CSC209: Software tools Unix files and directories permissions utilities/commands Shell programming quoting wild cards files 2 ... and C programming... C basic syntax functions

More information

Process. Signal #8. Signals are software interrupts from unexpected events. a power failure. an alarm clock. the death of a child process

Process. Signal #8. Signals are software interrupts from unexpected events. a power failure. an alarm clock. the death of a child process Linux/UNIX Programming 문양세강원대학교 IT특성화대학컴퓨터과학전공 Signals Signals are software interrupts from unexpected events an illegal operation (e.g., divide by 0) a power failure an alarm clock the death of a child

More information

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

UNIVERSITY OF TORONTO SCARBOROUGH Computer and Mathematical Sciences. APRIL 2016 EXAMINATIONS CSCB09H3S Software Tools & Systems Programming UNIVERSITY OF TORONTO SCARBOROUGH Computer and Mathematical Sciences APRIL 2016 EXAMINATIONS CSCB09H3S Software Tools & Systems Programming Instructor: Bianca Schroeder and Naureen Nizam Duration: 3 hours

More information

Hyo-bong Son Computer Systems Laboratory Sungkyunkwan University

Hyo-bong Son Computer Systems Laboratory Sungkyunkwan University Sockets Hyo-bong Son (proshb@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Client-Server Model Most network application is based on the client-server model: A server

More information

COMP/ELEC 429/556 Introduction to Computer Networks

COMP/ELEC 429/556 Introduction to Computer Networks COMP/ELEC 429/556 Introduction to Computer Networks Creating a Network Application Some slides used with permissions from Edward W. Knightly, T. S. Eugene Ng, Ion Stoica, Hui Zhang 1 How to Programmatically

More information

Signal Example 1. Signal Example 2

Signal Example 1. Signal Example 2 Signal Example 1 #include #include void ctrl_c_handler(int tmp) { printf("you typed CTL-C, but I don't want to die!\n"); int main(int argc, char* argv[]) { long i; signal(sigint, ctrl_c_handler);

More information

Memory-Mapped Files. generic interface: vaddr mmap(file descriptor,fileoffset,length) munmap(vaddr,length)

Memory-Mapped Files. generic interface: vaddr mmap(file descriptor,fileoffset,length) munmap(vaddr,length) File Systems 38 Memory-Mapped Files generic interface: vaddr mmap(file descriptor,fileoffset,length) munmap(vaddr,length) mmap call returns the virtual address to which the file is mapped munmap call unmaps

More information

CISC2200 Threads Spring 2015

CISC2200 Threads Spring 2015 CISC2200 Threads Spring 2015 Process We learn the concept of process A program in execution A process owns some resources A process executes a program => execution state, PC, We learn that bash creates

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

CS631 - Advanced Programming in the UNIX Environment Interprocess Communication II

CS631 - Advanced Programming in the UNIX Environment Interprocess Communication II CS631 - Advanced Programming in the UNIX Environment Slide 1 CS631 - Advanced Programming in the UNIX Environment Interprocess Communication II Department of Computer Science Stevens Institute of Technology

More information

Linux Programming

Linux Programming Linux Programming CMPT 433 Slides #6 Dr. B. Fraser 18-05-22 1 Topics 1) How can we do multitasking? 2) How can our multiple tasks communicate? 3) How can we communicate over the network? 18-05-22 2 Concurrency:

More information

Assignment 2 Group 5 Simon Gerber Systems Group Dept. Computer Science ETH Zurich - Switzerland

Assignment 2 Group 5 Simon Gerber Systems Group Dept. Computer Science ETH Zurich - Switzerland Assignment 2 Group 5 Simon Gerber Systems Group Dept. Computer Science ETH Zurich - Switzerland t Your task Write a simple file server Client has to be implemented in Java Server has to be implemented

More information

Chapter 4 Multithreaded Programming

Chapter 4 Multithreaded Programming Chapter 4 Multithreaded Programming Da-Wei Chang CSIE.NCKU Source: Abraham Silberschatz, Peter B. Galvin, and Greg Gagne, "Operating System Concepts", 9th Edition, Wiley. 1 1 Outline Overview Multithreading

More information

Εργαστήριο 9 I/O Multiplexing

Εργαστήριο 9 I/O Multiplexing Εργαστήριο 9 I/O Multiplexing Στοεργαστήριοθαμελετηθούν: Server High Level View I/O Multiplexing Solutions for Concurrency nonblocking I/O Use alarm and signal handler to interrupt slow system calls. Use

More information

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 DECEMBER 2017 EXAMINATIONS. CSC 209H1F Liu, Reid 3 hours. No Examination Aids PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science St. George Campus DECEMBER 2017 EXAMINATIONS CSC 209H1F Liu, Reid 3 hours PLEASE HAND IN No Examination Aids Student Number: Last (Family)

More information

Processes. Johan Montelius KTH

Processes. Johan Montelius KTH Processes Johan Montelius KTH 2017 1 / 47 A process What is a process?... a computation a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other

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

A process. the stack

A process. the stack A process Processes Johan Montelius What is a process?... a computation KTH 2017 a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other processes

More information

COSC243 Part 2: Operating Systems

COSC243 Part 2: Operating Systems COSC243 Part 2: Operating Systems Lecture 16: Threads and data sharing Zhiyi Huang Dept. of Computer Science, University of Otago Zhiyi Huang (Otago) COSC243 Lecture 16 1 / 24 Overview Last lecture: Hierarchical

More information

Interprocess Communication

Interprocess Communication Interprocess Communication Reading: Silberschatz chapter 4 Additional Reading: Stallings chapter 6 EEL 358 1 Outline Introduction Shared memory systems POSIX shared memory Message passing systems Direct

More information

CS 33. Signals Part 1. CS33 Intro to Computer Systems XXII 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

CS 33. Signals Part 1. CS33 Intro to Computer Systems XXII 1 Copyright 2017 Thomas W. Doeppner. All rights reserved. CS 33 Signals Part 1 CS33 Intro to Computer Systems XXII 1 Copyright 2017 Thomas W. Doeppner. All rights reserved. Whoops $ SometimesUsefulProgram xyz Are you sure you want to proceed? Are you really sure?

More information

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 CSC209 Review CSC209: Software tools Unix files and directories permissions utilities/commands Shell programming quoting wild cards files ... and systems programming C basic syntax functions arrays structs

More information

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

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files. Compiler vs. CSC209 Review CSC209: Software tools Unix files and directories permissions utilities/commands Shell programming quoting wild cards files... and systems programming C basic syntax functions arrays structs

More information

Ports under 1024 are often considered special, and usually require special OS privileges to use.

Ports under 1024 are often considered special, and usually require special OS privileges to use. 1 2 Turns out that besides an IP address (used by the IP layer), there is another address that is used by TCP (stream sockets) and, coincidentally, by UDP (datagram sockets). It is the port number. It's

More information

Interprocess Communication Mechanisms

Interprocess Communication Mechanisms Interprocess Communication 1 Interprocess Communication Mechanisms shared storage shared virtual memory shared files message-based sockets pipes signals Interprocess Communication 2 Message Passing Indirect

More information

Interprocess Communication Mechanisms

Interprocess Communication Mechanisms Interprocess Communication 1 Interprocess Communication Mechanisms shared storage shared virtual memory shared files message-based sockets pipes signals... Interprocess Communication 2 Message Passing

More information

Networked Applications: Sockets. End System: Computer on the Net

Networked Applications: Sockets. End System: Computer on the Net Networked Applications: Sockets Topics Programmer s view of the Internet Sockets interface End System: Computer on the Net Internet Also known as a host 2 Page 1 Clients and Servers Client program Running

More information

Lecture 4 Threads. (chapter 4)

Lecture 4 Threads. (chapter 4) Bilkent University Department of Computer Engineering CS342 Operating Systems Lecture 4 Threads (chapter 4) Dr. İbrahim Körpeoğlu http://www.cs.bilkent.edu.tr/~korpe 1 References The slides here are adapted/modified

More information

Overview. Administrative. * HW 1 grades. * HW 2 Due. Topics. * 5.1 What is a Signal? * Dealing with Signals - masks, handlers

Overview. Administrative. * HW 1 grades. * HW 2 Due. Topics. * 5.1 What is a Signal? * Dealing with Signals - masks, handlers Overview Administrative * HW 1 grades * HW 2 Due Topics * 5.1 What is a Signal? * 5.2-3 Dealing with Signals - masks, handlers * 5.4 Synchronization: pause(), sigsuspend() * 5.6 Interaction with other

More information

CSC209H Lecture 8. Dan Zingaro. March 4, 2015

CSC209H Lecture 8. Dan Zingaro. March 4, 2015 CSC209H Lecture 8 Dan Zingaro March 4, 2015 Signals you Already Know Like pipes, signals are a form of inter-process communication You ve already sent signals using the shell When you hit ctrl+c to terminate

More information

Signals. POSIX defines a variety of signal types, each for a particular

Signals. POSIX defines a variety of signal types, each for a particular Signals A signal is a software interrupt delivered to a process. The operating system uses signals to report exceptional situations to an executing program. Some signals report errors such as references

More information

Operating Systems. Threads and Signals. Amir Ghavam Winter Winter Amir Ghavam

Operating Systems. Threads and Signals. Amir Ghavam Winter Winter Amir Ghavam 95.300 Operating Systems Threads and Signals Amir Ghavam Winter 2002 1 Traditional Process Child processes created from a parent process using fork Drawbacks Fork is expensive: Memory is copied from a

More information

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 18

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 18 CS24: INTRODUCTION TO COMPUTING SYSTEMS Spring 2018 Lecture 18 LAST TIME: OVERVIEW Expanded on our process abstraction A special control process manages all other processes Uses the same process abstraction

More information

Problem 1: Concepts (Please be concise)

Problem 1: Concepts (Please be concise) Problem 1: Concepts (Please be concise) 1) Consider the use of threads vs. the select() system call for asynchronous I/O. Name one advantage of each approach. 2) Consider a dynamically allocated linked-list

More information

CS 350 : COMPUTER SYSTEM CONCEPTS SAMPLE TEST 2 (OPERATING SYSTEMS PART) Student s Name: MAXIMUM MARK: 100 Time allowed: 70 minutes

CS 350 : COMPUTER SYSTEM CONCEPTS SAMPLE TEST 2 (OPERATING SYSTEMS PART) Student s Name: MAXIMUM MARK: 100 Time allowed: 70 minutes CS 350 : COMPUTER SYSTEM CONCEPTS SAMPLE TEST 2 (OPERATING SYSTEMS PART) Student s Name: MAXIMUM MARK: 100 Time allowed: 70 minutes Q1 (30 marks) NOTE: Unless otherwise stated, the questions are with reference

More information

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

Socket Programming. #In the name of Allah. Computer Engineering Department Sharif University of Technology CE443- Computer Networks #In the name of Allah Computer Engineering Department Sharif University of Technology CE443- Computer Networks Socket Programming Acknowledgments: Lecture slides are from Computer networks course thought

More information

Any of the descriptors in the set {1, 4} have an exception condition pending

Any of the descriptors in the set {1, 4} have an exception condition pending Page 1 of 6 6.3 select Function This function allows the process to instruct the kernel to wait for any one of multiple events to occur and to wake up the process only when one or more of these events

More information

Preview. The pause() System Call. The pause() System Call. The signal() System Call 10/18/2017

Preview. The pause() System Call. The pause() System Call. The signal() System Call 10/18/2017 Preview The pause() System Call The pause() System call The signal() system call Signal set The sigprocmask() system call The sigaction() system call The sigsuspend() system call The abort() system call

More information

Redesde Computadores(RCOMP)

Redesde Computadores(RCOMP) Redesde Computadores(RCOMP) Theoretical-Practical (TP) Lesson 07 2016/2017 Berkeley sockets API, C and Java. Basic functions/methods for TCP applications. TCP client and server. Asynchronous reception.

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

CLIENT-SIDE PROGRAMMING

CLIENT-SIDE PROGRAMMING CLIENT-SIDE PROGRAMMING George Porter Apr 11, 2018 ATTRIBUTION These slides are released under an Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0) Creative Commons license These slides

More information

Section 3: File I/O, JSON, Generics. Meghan Cowan

Section 3: File I/O, JSON, Generics. Meghan Cowan Section 3: File I/O, JSON, Generics Meghan Cowan POSIX Family of standards specified by the IEEE Maintains compatibility across variants of Unix-like OS Defines API and standards for basic I/O: file, terminal

More information

Workshop on Inter Process Communication Solutions

Workshop on Inter Process Communication Solutions Solutions 1 Background Threads can share information with each other quite easily (if they belong to the same process), since they share the same memory space. But processes have totally isolated memory

More information

Preview. Process Termination. wait and waitpid() System Call. wait and waitpid() System Call. waitpid() System Call 10/23/2018

Preview. Process Termination. wait and waitpid() System Call. wait and waitpid() System Call. waitpid() System Call 10/23/2018 Preview Process Termination The waitpid() System Call The system() System Call Concept of Signals Linux Signals The signal System Call Unreliable Signals Signal() System Call The kill() and raise() System

More information

Programming Ethernet with Socket API. Hui Chen, Ph.D. Dept. of Engineering & Computer Science Virginia State University Petersburg, VA 23806

Programming Ethernet with Socket API. Hui Chen, Ph.D. Dept. of Engineering & Computer Science Virginia State University Petersburg, VA 23806 Programming Ethernet with Socket API Hui Chen, Ph.D. Dept. of Engineering & Computer Science Virginia State University Petersburg, VA 23806 9/14/2016 CSCI 445 Fall 2016 1 Acknowledgements Some pictures

More information

So far, we know how to create processes. How do we communicate with them? Primary mechanism: signals

So far, we know how to create processes. How do we communicate with them? Primary mechanism: signals Signals Page 1 Signals and handlers Thursday, September 14, 2017 11:58 AM So far, we know how to create processes. How do we communicate with them? Primary mechanism: signals Vocabulary Thursday, September

More information

n Unconditionally kill process 8371 n Interactive interrupt key n See /usr/include/bits/signum.h (e.g., SIGKILL 9) 2 -Ken Wong, Sep 2008

n Unconditionally kill process 8371 n Interactive interrupt key n See /usr/include/bits/signum.h (e.g., SIGKILL 9) 2 -Ken Wong, Sep 2008 Unix Signals (CSE 422S) Ken Wong Washington University kenw@wustl.edu www.arl.wustl.edu/~kenw The Signal Concept Generating Signals» Command Line: kill 9 8371 n Unconditionally kill process 8371 9: actual

More information

Redes de Computadores (RCOMP)

Redes de Computadores (RCOMP) Redes de Computadores (RCOMP) Theoretical-Practical (TP) Lesson 07 2017/2018 Berkeley sockets API, C and Java. Basic functions/methods for TCP applications. TCP client and server. Asynchronous reception.

More information

EEC-484/584 Computer Networks

EEC-484/584 Computer Networks EEC-484/584 Computer Networks Lecture 15 wenbing@ieee.org (Lecture nodes are based on materials supplied by Dr. Louise Moser at UCSB and Prentice-Hall) Outline 2 Review of last lecture The network layer

More information

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

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

CSMC 412. Computer Networks Prof. Ashok K Agrawala Ashok Agrawala Set 2. September 15 CMSC417 Set 2 1 CSMC 412 Computer Networks Prof. Ashok K Agrawala 2015 Ashok Agrawala Set 2 September 15 CMSC417 Set 2 1 Contents Client-server paradigm End systems Clients and servers Sockets Socket abstraction Socket

More information

Network Programming in C: The Berkeley Sockets API. Networked Systems 3 Laboratory Sessions

Network Programming in C: The Berkeley Sockets API. Networked Systems 3 Laboratory Sessions Network Programming in C: The Berkeley Sockets API Networked Systems 3 Laboratory Sessions The Berkeley Sockets API Widely used low-level C networking API First introduced in 4.3BSD Unix Now available

More information

ECE 650 Systems Programming & Engineering. Spring 2018

ECE 650 Systems Programming & Engineering. Spring 2018 ECE 650 Systems Programming & Engineering Spring 2018 User Space / Kernel Interaction Tyler Bletsch Duke University Slides are adapted from Brian Rogers (Duke) Operating System Services User and other

More information

Programming Ethernet with Socket API. Hui Chen, Ph.D. Dept. of Engineering & Computer Science Virginia State University Petersburg, VA 23806

Programming Ethernet with Socket API. Hui Chen, Ph.D. Dept. of Engineering & Computer Science Virginia State University Petersburg, VA 23806 Programming Ethernet with Socket API Hui Chen, Ph.D. Dept. of Engineering & Computer Science Virginia State University Petersburg, VA 23806 9/14/2015 CSCI 445 Fall 2015 1 Acknowledgements Some pictures

More information

CSE 410: Systems Programming

CSE 410: Systems Programming CSE 410: Systems Programming Input and Output Ethan Blanton Department of Computer Science and Engineering University at Buffalo I/O Kernel Services We have seen some text I/O using the C Standard Library.

More information

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2017 Lecture 19

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2017 Lecture 19 CS24: INTRODUCTION TO COMPUTING SYSTEMS Spring 2017 Lecture 19 LAST TIME Introduced UNIX signals A kernel facility that provides user-mode exceptional control flow Allows many hardware-level exceptions

More information

Systems Programming. 08. Standard I/O Library. Alexander Holupirek

Systems Programming. 08. Standard I/O Library. Alexander Holupirek Systems Programming 08. Standard I/O Library Alexander Holupirek Database and Information Systems Group Department of Computer & Information Science University of Konstanz Summer Term 2008 Last lecture:

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

NETWORK AND SYSTEM PROGRAMMING

NETWORK AND SYSTEM PROGRAMMING NETWORK AND SYSTEM PROGRAMMING LAB 09 Network Byte Ordering, inet_aton, inet_addr, inet_ntoa Functions Objectives: To learn byte order conversion To understand inet-aton, inet_addr, inet_ntoa Functions

More information

CS 640: Computer Networking

CS 640: Computer Networking CS 640: Computer Networking Yu-Chi Lai Lecture 3 Network Programming Topics Client-server model Sockets interface Socket primitives Example code for echoclient and echoserver Debugging With GDB Programming

More information

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

UNIVERSITY OF TORONTO Faculty of Arts and Science. St. George Campus APRIL 2012 EXAMINATIONS PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science St. George Campus APRIL 2012 EXAMINATIONS CSC 209H1S Instructors Michelle Craig and Karen Reid Duration 3 hours PLEASE HAND IN Examination

More information

Princeton University. Computer Science 217: Introduction to Programming Systems. Signals

Princeton University. Computer Science 217: Introduction to Programming Systems. Signals Princeton University Computer Science 217: Introduction to Programming Systems Signals 1 Goals of this Lecture Help you learn about: Sending signals Handling signals and thereby How the OS exposes the

More information

Standards / Extensions C or C++ Dependencies POSIX.1 XPG4 XPG4.2 Single UNIX Specification, Version 3

Standards / Extensions C or C++ Dependencies POSIX.1 XPG4 XPG4.2 Single UNIX Specification, Version 3 read() Read From a File or Socket z/os V1R10.0 XL C/C++ Run-Time Library Reference SA22-7821-10 Standards Standards / Extensions C or C++ Dependencies POSIX.1 XPG4 XPG4.2 Single UNIX Specification, Version

More information