异常控制流

进程控制

获取进程ID

import Darwin.POSIX.unistd

let processId = getpid()
let parentProcessId = getppid()

创建子进程和终止进程

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int main() {
    pid_t pid = fork();
    
    if (pid == 0) {
        printf("child\n");
        return 0;
    }
    
    printf("parent\n");
    exit(0);
    printf("will not print\n");
    return 0;
}

等待回收子进程

#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>

int main() {
    pid_t pid;
    for (int i = 0; i < 3; i++) {
        if ((pid = fork()) == 0) {
            return i;
        }
    }
    
    int status;
    while ((pid = waitpid(-1, &status, 0)) > 0) {
        if (WIFEXITED(status)) {
            printf("child %d ended with exit code: %d\n", pid, WEXITSTATUS(status));
        }
    }
    
    return 0;
}

进程休眠

import Darwin.POSIX.unistd

sleep(3)

加载并运行程序

import Darwin.POSIX.unistd

var argv0 = "ls".utf8CString
argv0.withUnsafeMutableBufferPointer {
    [$0.baseAddress, nil].withUnsafeBufferPointer {
        execve("/bin/ls", $0.baseAddress, nil)
    }
}

信号

import Darwin.POSIX.unistd

signal(SIGALRM) { _ in
    print("received alarm signal")
}

alarm(3)
pause()