c - 如何将程序发送到后台并停止执行?

标签 c linux

我是 C 信号处理的新手。所以我试图暂停程序执行并将其发送到后台,然后在发送 SIGCONT 时继续执行。不确定如何暂停程序。如果我要继续该程序,它也应该从中断处恢复。但我不确定如何实现这一点。我应该简单地使用 pause() 吗?任何建议将不胜感激,我只是在练习和玩弄信号处理。

void tSTP_handler(int signal){
    // not sure how to suspend program execution in handler and send it to background
}

int main(){
    signal(SIGTSTP, tSTP_handler);
    while(1){
         printf("Not suspended\n");
    }
    printf("resumed\n");
}

最佳答案

简单的步骤:

  1. 运行一个进程,并派生一个子进程,每 1ms 打印一次日志 子进程
  2. 发送一个信号(SIGSTOP,SIGCONT)给父进程的子进程 进程,在 SIGSTOP 和 SIGCONT 之间暂停 100ms
  3. 观察子进程的延迟。

代码:

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

#define MS 1000 // 1ms

long get_curr_time()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec * 1000000L + tv.tv_usec;
}

void do_child()
{
    int i = 0;
    long start, end, cost;
    for(i = 0; i < 3; i++) {
        start = get_curr_time();
        usleep(MS);
        end = get_curr_time();
        cost = end - start;
        if (cost > 2 * MS)
            printf("%d. cost time: %ld us, Delayed by SIGSTOP.\n", i, cost);
        else
            printf("%d. cost time: %ld us\n", i, cost);
    }
}

int main()
{
    int pid;
    pid = fork();
    if (pid == 0) {
        do_child();
    } else {
        usleep(2 * MS);

        kill(pid, SIGSTOP);     // pause 100ms
        usleep(100 * MS);
        kill(pid, SIGCONT);

        waitpid(pid, NULL, 0);
    }
    return 0;
}

结果:

0. cost time: 1066 us
1. cost time: 100886 us, Delayed by SIGSTOP.
2. cost time: 1057 us

关于c - 如何将程序发送到后台并停止执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54939798/

相关文章:

调用 BLAS 库中的 DDOT 函数

c++ - 可变函数的使用

linux - docker - 更改默认登录用户

linux - 计算行数并按前缀词分组

PHP & 庆典; Linux;编译我自己的函数

c - 为什么解引用运算符无法返回 "pointer to an array"变量指向的值?

c - C语言中如何用宏将符号转为文字?

c - 使用一个函数作为另一个函数的参数时的“error: invalid use of void expression”

linux - 如何可靠地为用户添加或附加到 PATH

Linux:恢复网络连接时执行命令