Velocerऐप खोलें

Velocer › फ़्लैशकार्ड › University of Illinois Urbana-Champaign › CS 341: System Programming · UIUC

CS 341: System Programming · UIUC

CS 341 notes turned into cards. not everything, just the stuff that kept coming up. · boneyard_cards द्वारा · 157 कार्ड्स

University of Illinois Urbana-Champaign

इस डेक का अध्ययन करें एम्बेड करें

  1. How does a C program communicate with the operating system?Through system calls, which request OS services such as memory allocation, process creation, and I/O.
  2. What is the relationship between C library I/O functions and POSIX calls?C library I/O functions like fprintf, fopen, puts, and getchar are built on top of low-level POSIX calls such as read, write, and open.
  3. What is a process?A process is a running instance of a program image, with its own address space.
  4. In which direction does the heap grow, and in which direction does the stack grow?The heap grows upward toward higher addresses, while the stack grows downward toward lower addresses.
  5. What is stored in the BSS segment of a process address space?Uninitialized global variables.
  6. What is stored in the code (text) segment?The program's executable instructions.
  7. Where in the address space are program arguments and environment variables located?At the top of the address space, above the stack.
  8. What is the difference between a program image and a process?A program image is the static executable file, while a process is a dynamic running instance of that file with its own address space.
  9. What does sizeof return for int A[8] on a typical system, and when is it evaluated?sizeof(A) is 8 times sizeof(int), and it is evaluated at compile time. sizeof(char) is always 1.
  10. What macro computes the number of elements in an array A?sizeof(A)/sizeof(A[0]) — it divides the total byte size by the size of one element.
  11. What does the C preprocessor do before compilation proper?It handles #include directives, #define macros, and conditional compilation.
  12. Why is #define max(a,b) a<b ? a : b dangerous, and how do you fix it?Macros are pure text substitution, so it breaks inside larger expressions. Wrap every argument and the whole body in parentheses.
  13. What is the difference between char *t1 = "hi"; and char t2[] = "abcdefgh";?t1 points at a read-only string literal (writing to it crashes); t2 copies the bytes into a writable stack array.
  14. What is wrong with malloc(n * sizeof(double*)) when you want an array of double?It allocates space for pointers, not doubles. Use sizeof(double) (or sizeof *ptr) instead.
  15. For a string p, what is p[strlen(p)]?It is the terminating '\0' character.
  16. What happens if you call strlen(NULL)?It is undefined behaviour — typically a crash.
  17. What are argv[0] and argv[argc]?argv[0] is the program's name; argv[argc] is NULL.
  18. Which standard string functions depend on the null terminator, and what extra requirement does strcat have?strcpy, strcat, strlen, and strcmp all depend on the null terminator. strcat also needs enough room in the destination buffer.
  19. How do asprintf, sprintf, and fprintf differ?asprintf allocates a big-enough buffer for the formatted string; sprintf writes into a buffer you supply; fprintf writes to a stream.
  20. What does assert(expr) do in debug builds versus when NDEBUG is defined?In debug builds it aborts with a message if the expression is false; when NDEBUG is defined it compiles away entirely.
  21. What is a dangling pointer, and how do you avoid one after free?A pointer that still points at freed memory. Set pointers to NULL after free, and never free the same memory twice.
  22. Which man section covers shell commands, system calls, and library functions?Section 1 for shell commands, 2 for system calls, 3 for library functions (e.g. man 2 stat).
  23. Why can writes to stderr and stdout appear out of order?stderr is unbuffered while stdout is usually line-buffered (to a terminal), so their output can interleave unpredictably.
  24. What does the read(fd, buf, count) system call return?The number of bytes read.
  25. How must destination arguments be passed to scanf?By address (as pointers), one for each format specifier.
  26. What does scanf return?The number of items successfully converted, or EOF.
  27. What does getline(&line, &cap, stream) do?Reads a whole line into a heap buffer.
  28. What happens when getline is called with line set to NULL and cap set to 0?getline allocates the buffer for you.
  29. Who is responsible for freeing the buffer allocated by getline?The caller, even if getline fails.
  30. What does getline return?The number of bytes read, or -1 at end of file or on error.
  31. What is the difference between sscanf and fscanf?sscanf parses from a string, while fscanf parses from a stream.
  32. What is the key difference between scanf and getline for reading input?scanf parses formatted input using format specifiers, while getline reads an entire line into a heap buffer.
  33. What does fork() do and what does it return in the child and parent?fork() duplicates the calling process. It returns 0 in the child, the child's PID in the parent, and -1 on failure.
  34. After fork(), is memory shared or copied between parent and child?Memory is copied, not shared. A change made in the child is invisible to the parent.
  35. What does the exec family of functions do, and when does exec return?exec replaces the current program image with a new program. It returns only if it fails.
  36. What is the difference between execvp/execlp and other exec variants?execvp and execlp search the PATH environment variable for the program. Other variants require an explicit path.
  37. How must the argument list passed to exec be terminated?The argument list must end with a NULL pointer.
  38. Describe the fork–exec–wait pattern.The parent forks a child, the child execs a new program, and the parent waits for the child to finish.
  39. What is the signature of waitpid and how do you check if the child exited normally?waitpid(pid, &status, options). Use WIFEXITED(status) to check normal exit, then WEXITSTATUS(status) to get the exit code.
  40. How do you detect and retrieve the signal that terminated a child?Use WIFSIGNALED(status) to check if the child was killed by a signal, then WTERMSIG(status) to get the signal number.
  41. What do getpid() and getppid() return?getpid() returns the calling process's PID; getppid() returns its parent's PID.
  42. What is a zombie process?A finished child whose parent has not yet waited on it. It still holds an entry in the process table.
  43. What is an orphan process and what happens to it?A child whose parent died first. It is re-parented to init (PID 1).
  44. What signal does the parent receive when a child terminates?SIGCHLD.
  45. Why might output print twice after a fork?Unflushed stdout buffers are duplicated by fork, so buffered text can be printed by both processes.
  46. How are environment variables accessed in a C process?They form a per-process dictionary accessible via getenv("PATH") or the extern char **environ array.
  47. What is a signal in Unix/Linux?An asynchronous notification sent to a process, either by the kernel (e.g., SIGSEGV for illegal memory access) or by another process or user via kill.
  48. Which two signals can never be caught, masked, or ignored?SIGKILL and SIGSTOP. No handler, mask, or ignore setting can affect them.
  49. What does SIGINT represent and can it be caught?SIGINT is generated by Ctrl-C and is catchable (unlike SIGKILL or SIGSTOP).
  50. What are the purposes of SIGSTOP and SIGCONT?SIGSTOP suspends a process and cannot be caught; SIGCONT resumes a stopped process.
  51. Which signal is delivered by the alarm() function?SIGALRM.
  52. How do you send a signal to a process from C and from the shell?In C use kill(pid, sig); in the shell use kill -SIG pid.
  53. What is the safe pattern for writing a signal handler?The handler should only set a flag (ideally volatile sig_atomic_t) and let the main loop act on it, because most library calls like printf are unsafe inside handlers.
  54. Why is calling printf inside a signal handler unsafe?Most library calls, including printf, are not async-signal-safe, so calling them in a handler can cause undefined behavior.
  55. What is the recommended type for a flag set by a signal handler?volatile sig_atomic_t, which ensures the flag is accessed atomically and not optimized away.
  56. Which signal is sent when a child process changes state, and which indicates a broken pipe?SIGCHLD indicates a child process state change; SIGPIPE indicates writing to a pipe with no reader.
  57. What is SIGQUIT and how does it differ from SIGINT?SIGQUIT is a catchable termination signal, typically generated by Ctrl-\, whereas SIGINT comes from Ctrl-C.
  58. What does malloc return, and how does it differ from calloc?malloc returns uninitialized memory; calloc(count, size) returns zeroed memory.
  59. What does realloc(ptr, size) do to an existing block?It resizes the block, possibly moving it to a new location, and returns a pointer to the resized memory.
  60. What does sbrk(n) do and what does it return?It grows the data segment (heap) by n bytes and returns the old break; sbrk(0) reports the current top.
  61. Why does a naive allocator that only calls sbrk and never reuses memory waste space?Because freed memory is never reused, so all released space is effectively lost.
  62. What is the first fit placement strategy?Allocate into the first free hole that is big enough.
  63. What is the best fit placement strategy?Allocate into the smallest free hole that fits the request.
  64. What is the worst fit placement strategy?Allocate into the largest free hole available.
  65. What is internal fragmentation?Wasted space inside an allocated block.
  66. What is external fragmentation?Enough total free memory exists but it is not in one contiguous piece.
  67. How does splitting a free block help?It avoids internal waste by allocating only the needed portion and leaving the remainder as a smaller free block.
  68. How does coalescing fight fragmentation?It merges adjacent free blocks to combat external fragmentation.
  69. Why is metadata stored immediately before the user pointer?So free can find the block's metadata in O(1) time.
  70. How do implicit free lists traverse blocks?They step from block to block by adding each block's size.
  71. How do explicit free lists differ from implicit ones?Explicit lists keep next/prev pointers inside free blocks rather than relying on size arithmetic.
  72. What are boundary tags (Knuth) and what two purposes do they serve?The size is copied at both ends of each block so neighbours can be found and merged in constant time; they can also act as canaries to detect overflow.
  73. Why do allocators round sizes up (e.g., to 16 bytes)?For alignment so any type can be stored; misaligned access can cause a bus error.
  74. When can realloc grow a block in place?When the next block is free and large enough.
  75. What are the four goals of an allocator?Compact representation, fast allocation, fast recycling, and high utilization.
  76. What does each thread have its own copy of, and what does it share with other threads in the same process?Each thread has its own stack and registers, but shares the process's heap, global variables, and code.
  77. What does pthread_join do?It waits for the specified thread to terminate and collects its return value via the retval pointer.
  78. What does pthread_exit do?It terminates only the calling thread, allowing other threads in the process to keep running.
  79. What compiler flag is needed to link a program that uses POSIX threads?-pthread
  80. What is the difference between exit() and pthread_exit() when called from main?exit() terminates the entire process, while pthread_exit() in main ends only the main thread so other threads can continue.
  81. Why is passing &i from a loop to multiple threads a race condition?All threads read the same variable i, so they may see the same or changing value; each thread should get a distinct heap or array element instead.
  82. Is malloc thread-safe?Yes; two threads can call malloc concurrently and receive different blocks.
  83. What does it mean for work to be embarrassingly parallel?The work splits into independent tasks that can run concurrently without coordination, such as Mandelbrot rows or tiles.
  84. When parallelizing embarrassingly parallel work, should you create one thread per task?No; cap the number of threads rather than creating one per row or task.
  85. What is a common safe way to pass per-thread data to a start routine?Pass a distinct heap-allocated value or an array element (e.g., a task struct) for each thread instead of a shared loop variable.
  86. What is a race condition?A race condition occurs when threads access shared memory concurrently and the result depends on timing, such as two threads each incrementing a counter a million times and losing updates.
  87. What is a critical section?Code that only one thread may execute at a time.
  88. What does a mutex do?A mutex enforces mutual exclusion, allowing only one thread into a critical section at a time.
  89. What happens when a thread calls pthread_mutex_lock on a held mutex?It blocks until the lock becomes free.
  90. Which function releases a mutex?pthread_mutex_unlock releases the mutex.
  91. How can a mutex be created in pthreads?With the PTHREAD_MUTEX_INITIALIZER static initializer or by calling pthread_mutex_init.
  92. When is it safe to destroy a mutex?Only when no thread holds or is waiting on it.
  93. What three requirements must a critical section solution satisfy?Mutual exclusion, progress, and bounded waiting.
  94. What does Peterson's solution use to achieve mutual exclusion?It combines a turn variable with per-thread flags.
  95. What kind of hardware instruction do real locks rely on?An atomic instruction such as exchange or compare-and-swap.
  96. What is a condition variable used for?It lets a thread sleep until some condition may have changed, avoiding busy-waiting.
  97. Why should a condition variable wait be inside a while loop rather than an if?Because wakeups can be spurious and the condition may be false again, so the predicate must be rechecked.
  98. What does pthread_cond_wait do with the mutex?It atomically releases the mutex and sleeps; on wakeup it reacquires the mutex before returning.
  99. What is the difference between pthread_cond_signal and pthread_cond_broadcast?pthread_cond_signal wakes one waiter; pthread_cond_broadcast wakes all waiters.
  100. How does a counting semaphore's sem_wait behave?It decrements the count and blocks when the count is zero.
  101. How does sem_post behave, and why is it special?It increments the count and never blocks; it is safe to call inside a signal handler.
  102. In a producer–consumer ring buffer, what do the two semaphores count?One counts empty slots (initialized to capacity), the other counts filled slots (initialized to 0).
  103. What synchronization is needed around the in/out indices in a ring buffer?A mutex protects the in/out indices.
  104. What does a barrier do?Every thread waits until all threads have arrived, then all continue together.
  105. What functions or constructs can implement a barrier?pthread_barrier_wait, or a counter combined with a condition variable.
  106. What is the reader–writer problem?Many readers may share access simultaneously, but a writer needs exclusive access.
  107. What does a writer-priority reader–writer solution track?It tracks waiting and active readers and writers to give writers priority.
  108. Which library type implements reader–writer locks?pthread_rwlock_t.
  109. What is a deadlock?A set of processes each wait for a resource held by another in the set, so none can proceed.
  110. What are the four Coffman conditions for deadlock?Mutual exclusion, hold and wait, no preemption, and circular wait. All four must hold for deadlock to occur.
  111. What does the mutual exclusion condition mean?A resource can be held by only one process at a time.
  112. What does the hold and wait condition mean?A process holds one resource while requesting additional resources.
  113. What does the no preemption condition mean?A resource is released only voluntarily by the process holding it.
  114. What does the circular wait condition mean?A cycle of processes exists where each waits on a resource held by the next.
  115. How can deadlock be prevented by breaking a Coffman condition?Break any one condition, e.g. acquire locks in a fixed global order (order mutexes by address) or let the OS preempt resources.
  116. What is livelock?Processes keep changing state (e.g., releasing and retrying) but make no progress.
  117. How does livelock differ from deadlock?In livelock processes are active and changing state but still make no progress, whereas in deadlock processes are blocked waiting.
  118. Describe the dining philosophers problem.Five philosophers sit around a table with five chopsticks; each needs two chopsticks to eat. A naive left-then-right acquisition causes deadlock.
  119. What fixes exist for the dining philosophers deadlock?A global ordering of chopsticks (Dijkstra's partial order), limiting how many philosophers may sit (Stallings), or using an arbitrator.
  120. What problem can try-lock-and-back-off cause in the dining philosophers scenario?It can cause livelock, since philosophers keep releasing and retrying without making progress.
  121. What does the Banker's algorithm do?It grants a request only if the system remains in a safe state after the allocation.
  122. What is a safe state in the context of the Banker's algorithm?A state in which there exists some sequence of process completions that lets all processes finish without deadlock.
  123. What does the MMU do with virtual addresses?The MMU translates virtual addresses to physical frames using a page table.
  124. With 32-bit addresses and 4 KB pages, how large is a single-level page table?It has 2^20 entries; at 4 bytes each that is 4 MB per process.
  125. What advantage does a two-level page table have over a single-level one?It only allocates the page-table pieces actually used, saving memory.
  126. What is the purpose of the TLB?The TLB caches recent virtual-to-physical translations to avoid page-table reads.
  127. What does the dirty bit in a page table indicate?The page was modified and must be written back to disk before eviction.
  128. What happens when a process writes to a page marked read-only?A page fault is triggered, and the kernel handles it.
  129. When does a page fault occur?When the page is not in RAM (e.g., swapped out) or the access violates protections.
  130. Give examples of how processes can share physical frames.Shared frames can hold the C library, copy-on-write pages after fork, or memory mapped with MAP_SHARED.
  131. List common IPC options.Pipes, named pipes (FIFOs), shared memory via mmap, files, signals, and sockets.
  132. What is a named pipe also called?A FIFO.
  133. Which page-table bit prevents execution of code from a page?The no-execute bit.
  134. What does pipe(fds) return in fds[0] and fds[1]?fds[0] is the read end and fds[1] is the write end of the pipe.
  135. Why must each process close the pipe ends it does not use after fork?Otherwise the readers never see end-of-file, because a write end remains open somewhere.
  136. What happens when you write to a pipe with no remaining readers?The write raises SIGPIPE.
  137. What does dup2(oldfd, newfd) do?It makes newfd refer to the same open file as oldfd, commonly used to redirect stdin/stdout to a pipe or file.
  138. What does fdopen(fd, mode) do?It wraps a file descriptor in a FILE* stream.
  139. What does a C library FILE hold to reduce write calls?A buffer and a buffering mode (unbuffered, line-buffered, or fully buffered).
  140. What is the purpose of fflush?It writes out the stream's buffered data.
  141. What underlying system call do fseek and ftell use?They use lseek underneath.
  142. What are the three fseek whence values?SEEK_SET, SEEK_CUR, and SEEK_END.
  143. Do forked processes share the file offset of descriptors opened before the fork?Yes, forked processes share the file offset of descriptors opened before the fork.
  144. How do pread and pwrite differ from ordinary reads and writes regarding the file offset?They take an explicit offset and do not move the shared file offset.
  145. What do fread and fwrite do?They move binary records to and from a stream.
  146. Why use fixed-width types like uint32_t in file formats?They make file formats portable across systems with different type sizes.
  147. What does errno represent, and is it shared between threads?errno holds the error code set by a failing call. It is per-thread, so each thread has its own value.
  148. What do perror and strerror do?They convert an errno value into a human-readable text message. perror prints it, while strerror returns the string.
  149. When should you check errno?Only immediately after a call fails, because successful calls may leave old values in errno.
  150. What does the EINTR error mean?A blocking call such as read, write, sem_wait, or sleep was interrupted by a signal. The usual fix is to retry the call in a loop.
  151. Why might write write fewer bytes than requested?Partial writes can happen, especially on sockets. A write_all loop keeps writing until every byte has been sent.
  152. What is a write_all loop used for?It repeatedly calls write until all requested bytes are sent, handling partial writes.
  153. What are the key characteristics of UDP?UDP is connectionless and sends datagrams with no delivery or ordering guarantees, but has low overhead.
  154. What are the key characteristics of TCP?TCP is connection-based and provides a reliable, ordered byte stream.
  155. Which protocol guarantees ordered, reliable delivery: TCP or UDP?TCP guarantees reliable, ordered delivery. UDP provides neither.
  156. Which protocol is connectionless and has lower overhead?UDP is connectionless and has lower overhead than TCP.
  157. What is the difference between TCP and UDP in terms of data units?TCP delivers a continuous ordered byte stream. UDP sends individual datagrams.

Velocer मुफ़्त है: स्पेस्ड रिपिटिशन और किसी भी दस्तावेज़ से अपने खुद के कार्ड।

PDF to flashcards · Lecture to flashcards · Practice exam · Syllabus study plan · Anki import

University of Illinois Urbana-Champaign के और डेक