c语言中如何使用term进行进程控制

   2024-09-30 2430
核心提示:在C语言中,你可以使用terminate()函数来终止一个进程#includestdio.h#include stdlib.h#includesignal.h#include unistd.h#incl

在C语言中,你可以使用terminate()函数来终止一个进程

#include<stdio.h>#include <stdlib.h>#include<signal.h>#include <unistd.h>#include <sys/types.h>#include <sys/wait.h>void handler(int signum) {    printf("Received signal %d, exiting...\n", signum);    exit(0);}int main() {    pid_t pid;    int status;    // 创建一个子进程    if ((pid = fork()) < 0) {        perror("fork error");        exit(1);    }    // 子进程执行这里的代码    if (pid == 0) {        // 设置信号处理器        signal(SIGTERM, handler);        // 子进程无限循环,直到收到SIGTERM信号        while (1) {            printf("Child process is running...\n");            sleep(1);        }    }    // 父进程执行这里的代码    else {        printf("Parent process created child process with PID %d\n", pid);        sleep(5);        // 向子进程发送SIGTERM信号        if (kill(pid, SIGTERM) < 0) {            perror("kill error");            exit(1);        }        // 等待子进程结束        wait(&status);        printf("Child process terminated with status %d\n", WEXITSTATUS(status));    }    return 0;}

在这个示例中,我们首先创建了一个子进程。子进程会无限循环,直到收到SIGTERM信号。我们为子进程设置了一个信号处理器,当收到SIGTERM信号时,它会打印一条消息并退出。

父进程在创建子进程后,等待5秒钟,然后向子进程发送SIGTERM信号。接着,父进程等待子进程结束,并打印子进程的退出状态。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号