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

问题描述 投票:0回答:1

我是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");
}
c linux
1个回答
1
投票

简单的步骤:

  1. 运行一个进程,并fork一个子进程,在子进程上每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
© www.soinside.com 2019 - 2024. All rights reserved.