There are two parts to networking within QEMU:
- The virtual network device that is provided to the guest (e.g. a PCI network card).
- The network backend that interacts with the emulated NIC (e.g. puts packets onto the host's network).
#!/bin/bash | |
PREFIX=/home/jake/mount_1TB/gns3server | |
ISO=${PREFIX}/ubuntu-20.04.3-live-server-amd64.iso # Installation media | |
NET=br0 # bridge name | |
OS=linux # os type | |
VM_DISK=${PREFIX}/kvm-generic.qcow2 # VM image on disk | |
sudo qemu-system-x86_64 \ | |
-machine type=q35,accel=hvf \ | |
-smp 2 \ | |
-hda ${VM_DISK}\ |
在 GNU/Linux 環境,假設我們編譯的程式都會動態連結到 glibc 提供的 libc.so.6,考慮以下程式碼: (檔名: fork.c) | |
#include <stdio.h> | |
#include <unistd.h> | |
int main(void) | |
{ | |
for (int i = 0; i < NNN; i++) { | |
fork(); | |
printf("-"); |
以下程式碼可針對給定的 alignment 數值,輸出大於等於 alignment 的記憶體對齊地址: | |
#include <stdint.h> | |
static inline uintptr_t align_up(uintptr_t sz, size_t alignment) | |
{ | |
uintptr_t mask = alignment - 1; | |
if ((alignment & mask) == 0) { /* power of two? */ | |
return MMM; | |
} |
// 以下程式碼可建立針對不同位元的向左/向右位元旋轉的實作: | |
#include <stdint.h> | |
#define __DECLARE_ROTATE(bits, type) \ | |
static inline type rotl##bits(const type v, int c) \ | |
{ \ | |
const int mask = (bits) - (1); \ | |
c &= mask; \ | |
\ |
用二進位來表示和處理內部數值,考慮階乘 (factorial) 運算: | |
/* | |
* factorial(N) := N * (N-1) * (N-2) * ... * 1 | |
*/ | |
static void factorial(struct bn *n, struct bn *res) { | |
struct bn tmp; | |
bn_assign(&tmp, n); | |
bn_dec(n); | |
while (!bn_is_zero(n)) { |
考慮以下仿效 Linux 核心 include/linux/list.h 的精簡實作: | |
/** | |
* container_of() - Calculate address of object that contains address ptr | |
* @ptr: pointer to member variable | |
* @type: type of the structure containing ptr | |
* @member: name of the member variable in struct @type | |
* | |
* Return: @type pointer of object containing ptr | |
*/ |
考慮函式 func 接受一個 16 位元無號整數 N,並回傳小於或等於 N 的 power-of-2 | |
實作程式碼如下: | |
uint16_t func(uint16_t N) { | |
/* change all right side bits to 1 */ | |
N |= N >> 1; | |
N |= N >> X; | |
N |= N >> Y; | |
N |= N >> Z; |
user-level thread 又稱為 fiber,設計動機是提供比原生執行緒 (native thread) 更小的執行單元。 | |
我們嘗試透過 Linux clone 系統呼叫,來實作 fiber。 | |
給定以下程式碼: | |
static void fibonacci() { | |
int fib[2] = {0, 1}; | |
printf("Fib(0) = 0\nFib(1) = 1\n"); | |
for (int i = 2; i < 15; ++i) { | |
int nextFib = fib[0] + fib[1]; |
給定一個陣列 nums 和一個目標值 target,求找到 nums 的 2 個元素相加會等於 target 的索引值。題目確保必為單一解,且回傳索引的順序沒差異。 | |
例如給定輸入 nums = [2, 11, 7, 15], target = 9,相加變成 9 的元素僅有 2 及 7,因此回傳這二個元素的索引值 [0, 2] | |
考慮以下 C O(n^2)語言實作: | |
#include <stdlib.h> | |
static int cmp(const void *lhs, const void *rhs) { | |
if (*(int *) lhs == *(int *) rhs) | |
return 0; | |
return *(int *) lhs < *(int *) rhs ? -1 : 1; |