linux

Linux进程管理:如何创建和终止进程

小樊
50
2025-08-04 22:04:48
栏目: 智能运维

在Linux系统中,创建和终止进程是基本的操作。以下是一些常用的方法:

创建进程

  1. 使用fork()系统调用fork()系统调用用于创建一个新的进程。新进程(子进程)是父进程的副本,拥有相同的代码、数据段、堆栈等。

    #include <stdio.h>
    #include <unistd.h>
    
    int main() {
        pid_t pid = fork();
        if (pid == -1) {
            // 错误处理
            perror("fork");
            return 1;
        } else if (pid == 0) {
            // 子进程
            printf("I am the child process, my PID is %d\n", getpid());
        } else {
            // 父进程
            printf("I am the parent process, my PID is %d and my child's PID is %d\n", getpid(), pid);
        }
        return 0;
    }
    
  2. 使用exec()系列函数exec()系列函数(如execl(), execp(), execv()等)用于在当前进程的上下文中加载并运行一个新的程序。

    #include <stdio.h>
    #include <unistd.h>
    
    int main() {
        pid_t pid = fork();
        if (pid == -1) {
            // 错误处理
            perror("fork");
            return 1;
        } else if (pid == 0) {
            // 子进程
            char *args[] = {"ls", "-l", NULL};
            execvp(args[0], args);
            // 如果execvp返回,说明出错了
            perror("execvp");
            return 1;
        } else {
            // 父进程
            printf("Parent process waiting...\n");
            wait(NULL); // 等待子进程结束
            printf("Parent process finished.\n");
        }
        return 0;
    }
    

终止进程

  1. 使用exit()系统调用exit()系统调用用于终止当前进程并返回一个状态码。

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        printf("Exiting process...\n");
        exit(0); // 返回状态码0表示正常退出
    }
    
  2. 使用kill()系统调用kill()系统调用用于向指定进程发送信号。常用的信号有SIGTERM(请求进程终止)和SIGKILL(强制终止进程)。

    #include <stdio.h>
    #include <stdlib.h>
    #include <signal.h>
    #include <sys/types.h>
    #include <unistd.h>
    
    int main() {
        pid_t pid = fork();
        if (pid == -1) {
            // 错误处理
            perror("fork");
            return 1;
        } else if (pid == 0) {
            // 子进程
            printf("Child process PID: %d\n", getpid());
            sleep(10); // 子进程休眠10秒
        } else {
            // 父进程
            printf("Parent process PID: %d\n", getpid());
            sleep(2); // 父进程休眠2秒
            kill(pid, SIGTERM); // 发送SIGTERM信号给子进程
            // 或者使用kill(pid, SIGKILL); 强制终止子进程
        }
        return 0;
    }
    
  3. 使用pkill()命令pkill()命令用于根据进程名称或其他属性终止进程。

    pkill -f process_name
    
  4. 使用killall()命令killall()命令用于根据进程名称终止所有匹配的进程。

    killall process_name
    

这些方法可以帮助你在Linux系统中创建和终止进程。根据具体需求选择合适的方法。

0
看了该问题的人还看了