# linux2021: mucrolores ## 測驗 $\beta - 1$ ```c static inline uintptr_t align_up(uintptr_t sz, size_t alignment) { uintptr_t mask = alignment - 1; if ((alignment & mask) == 0) { /* check if alignment is power of 2 */ return ((sz+mask)&(~mask)); } return (((sz + mask) / alignment) * alignment); } ``` 這段程式碼中主要的部份就是以`((sz+mask)&(~mask))` 為主要核心 sz+mask 會讓所有小於等於下一個alignment且大於前一個alignment的 都變成大於等於下一個alignment ex: ``` 120 + 3 = 123 // next alignment: 120 121 + 3 = 124 // next alignment: 124 122 + 3 = 125 // next alignment: 124 123 + 3 = 126 // next alignment: 124 124 + 3 = 127 // next alignment: 124 ``` 之後直接取 `&(~mask)` 相當於直接把mask的bit都移除掉 類似 `k >> (bit_of_mask) << (bit_of_mask)` 的作用 達到最後所需要的效果 ## 測驗 $\gamma - 1$ ``` c #include <stdio.h> #include <unistd.h> int main(void) { for (int i = 0; i < NNN; i++) { fork(); printf("-"); } fflush(stdout); return 0; } ``` 因為在執行`fork()`的過程中會複製到很多東新到新的process, stdio中的buffer也是,在stdio中,執行`printf()`時,只要沒有遇到 `\n` 或是執行 `fflush(stdout)`,其實資料就會先暫時放在stdio的buffer中,所以呼叫 `fork()`的時候 就會把先前 `printf("-");` 也複製到新的process。 所以在迴圈執行的過程中可以簡化為下列的式子。 ``` i = 0, p = 2, char per buf = 1, buf_total = 2 i = 1, p = 4, char per buf = 2, buf_total = 8 i = 2, p = 8, char per buf = 3, buf_total = 24 i = 3, p = 16, char per buf = 4, buf_total = 64 i = 4, p = 32, char per buf = 5, buf_total = 160 i = 5, p = 64, char per buf = 6, buf_total = 384 i = 6, p = 128, char per buf = 7, buf_total = 896 i = 7, p = 256, char per buf = 8, buf_total = 2048 i = 8, p = 512, char per buf = 9, buf_total = 4608 i = 9, p = 1024, char per buf = 10, buf_total = 10240 i = 10, p = 2048, char per buf = 11, buf_total = 22528 i = 11, p = 4096, char per buf = 12, buf_total = 49152 ``` 就會形成最後的結果