Cheat
Cheat
- Allowed Materials:
- A4-size double-sided handwritten/printed notes.
- Calculator.
- Scratch paper provided.
---
Processes
Zombie vs. Orphan Process
Zombie Process: A process that has terminated but whose parent hasn’t called wait().
Orphan Process: A child process whose parent has terminated.
Code Examples:
```c
// Zombie process
int main() {
if (fork() == 0) {
exit(0); // Child exits
} else {
while (1); // Parent doesn't call wait()
}
}
// Orphan process
int main() {
if (fork() == 0) {
while (1); // Child loops forever
} else {
exit(0); // Parent exits
}
}
```
---
Signal Handling
Common Signals:
- SIGKILL: Terminates a process (cannot be caught or ignored).
- SIGSEGV: Sent when a process makes an illegal memory access.
Signal Workflow:
1. Signal received by process.
2. Control passes to the signal handler.
3. Signal handler executes.
4. Control returns to the next instruction.
```c
#include <signal.h>
#include <stdio.h>
int main() {
signal(SIGINT, sig_handler); // Handle Ctrl+C
while (1);
}
```
Pipes
Parent-Child Communication:
- Use pipe().
- Close unused ends in each process.
Example:
```c
int main() {
int fd[2];
pipe(fd); // Create pipe
if (fork() == 0) {
close(fd[1]); // Close write end in child
char buf[100];
read(fd[0], buf, sizeof(buf));
printf("Child received: %s\n", buf);
} else {
close(fd[0]); // Close read end in parent
write(fd[1], "Hello, child!", 14);
}
return 0;
}
```
---
```c
#include <pthread.h>
#include <semaphore.h>
sem_t semaphore;
int main() {
pthread_t threads[2];
sem_init(&semaphore, 0, 1); // Initialize with 1
sem_destroy(&semaphore);
return 0;
}
```
---
Network Programming
Socket API
Server Workflow:
1. socket()
2. bind()
3. listen()
4. accept()
5. recv()
6. send()
7. close()
Client Workflow:
1. socket()
2. connect()
3. send()
4. recv()
5. close()
---
Design Questions: Focus on using processes, threads, signals, and shared resources efficiently.
Example:
- "How would you design a multi-threaded server to handle 1000 clients?"
---
---
PART 5: Programming
Project 4 Recap
Simulated Parallel Processing:
- Pipes for communication.
- Signals for task completion.
---
Quick Reference:
- Common System Calls:
- fork(), wait(), exec(), pipe(), signal(), kill()
- Thread Functions:
- pthread_create(), pthread_join(), pthread_exit(), sem_wait(), sem_post()
- Socket API:
- socket(), bind(), listen(), accept(), connect(), recv(), send()
Practice code tracing and understand the core concepts! Good luck!