Linux进程创建和管理

在 Linux 中,进程创建和管理的相关函数主要是 fork()exec()wait()exit()

 

举个例子:

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

int main() {
    pid_t pid;

    // 创建子进程
    pid = fork();

    if (pid < 0) {
        // 出错处理
        perror("fork failed");
        exit(EXIT_FAILURE);
    } else if (pid == 0) {
        // 子进程代码
        printf("Child process with PID: %d\n", getpid());
        // 替换当前进程的代码段
        execlp("/bin/ls", "ls", NULL);
        // 如果 execlp() 失败,则会执行以下代码
        perror("execlp failed");
        exit(EXIT_FAILURE);
    } else {
        // 父进程代码
        printf("Parent process with PID: %d\n", getpid());
        // 等待子进程结束
        wait(NULL);
        printf("Child process terminated\n");
    }

    // 退出当前进程
    printf("Exiting...\n");
    exit(EXIT_SUCCESS);
}

 

执行结果如下:

 

posted @ 2024-04-04 09:21  lethe1203  阅读(3)  评论(0编辑  收藏  举报