---
# System prepended metadata

title: Process
tags: [OS]

---

<style>
H2{color:#BF0060 !important;}
H3{color:#009393 !important;}
p{color:Black !important;}
li strong {color:#4682b4 !important;}
</style>

# Process
## **TCP Echo Server & Client** 
### **Socket**
* **listeing socket**
    * `Requested by server program`
    * `accept incoming connections`
* **connected socket**
    * `created by kernal`
    * `communicate with the connected socket`
        * <img src="https://i.imgur.com/BE3CGHZ.png" width = "200"/></img>
### ***Echo Client***
* **問題**
    * 無法同時 wait 兩個 blocking system call
        * client 使用了 fgets(stdin) 和 readline(sockfd) 
### ***Echo Client (Ver. 1)***
* **解法**
    * Stop-and-Wait (Interactive) Mode
        * Echo Client輪流處理stdin輸入與socket輸入
### ***Echo Client (Ver. 2)***
* **解法**
    * call select
    * <img src="https://i.imgur.com/BfDDwDc.png" width = "400"/></img>
### ***Echo Client (Ver. 3)***
* **解法**
    * maintain data strutcture(2 queue)
    * <img src="https://i.imgur.com/uthYIc5.png" width = "400"/></img>



## **IPC** 
### **Intro**
* linux 五種常用的IPC (inter-processes communication)
    * pipe
    * shared memory
    * ==signal==
    * message queue
    * domain socket
### **Signal**
* **software interrupt**
    * `process to process 或 kernal to process (SIGCHILD)`
* **signal handler**
    * `call sigaction`
        * 向 kernel 註冊自己的 signal handler
        * SIG_IGN: ignore it
        * SIG_DFL: default: terminate or ignore
* **問題**
    * `signalhandler 禁止重進入，其他 signal 來會被 block`
    * `Mostly, signals are not queued，所以多個 same signal 只會觸發 handler 1 次`
* **解法：waitpid 取代 wait**
    * `wait 會 block caller, whereas waitpid has an option (WNOHANG) that prevents it from blocking`
    * `用 while loop 把多個 child 的 status 抓回來`
        * while ( (pid = waitpid(-1, &stat, WNOHANG)) > 0)


###### tags: `OS`