我是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");
}
答案 0 :(得分:1)
简单步骤:
代码:
#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