我是 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");
}
最佳答案
简单的步骤:
- 运行一个进程,并派生一个子进程,每 1ms 打印一次日志 子进程
- 发送一个信号(SIGSTOP,SIGCONT)给父进程的子进程 进程,在 SIGSTOP 和 SIGCONT 之间暂停 100ms
- 观察子进程的延迟。
代码:
#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/