如果您有一些将向它发送信号的代码,那么您代码上的这个变体(我称之为它sleepers-awake.c
)将起作用:
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
static sig_atomic_t caught = 0;
static void snooze(unsigned int secs)
{
unsigned int timeleft = secs;
printf("Sleeping for %u\n", timeleft);
while ((timeleft = sleep(timeleft)) != 0)
{
printf("Slept for %d of %d secs (signal %d)\n", secs - timeleft, secs, caught);
caught = 0;
printf("Sleeping for %u\n", timeleft);
}
}
static void catcher(int signum)
{
signal(signum, catcher);
caught = signum;
}
int main(void)
{
signal(SIGINT, catcher);
snooze(5);
return 0;
}
迷你庞巴迪
小型化程序运行另一个程序并以 1 秒的间隔用信号轰炸它。
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
int main(void)
{
pid_t pid = fork();
if (pid < 0)
return 1;
if (pid == 0)
{
char *argv[] = { "./sleepers-awake", 0 };
execv(argv[0], argv);
fprintf(stderr, "Failed to execute %s\n", argv[0]);
return 1;
}
else
{
for (int i = 0; i < 5; i++)
{
sleep(1);
kill(pid, SIGINT);
}
}
return 0;
}
示例输出
Sleeping for 5
Slept for 0 of 5 secs (signal 2)
Sleeping for 5
Slept for 1 of 5 secs (signal 2)
Sleeping for 4
Slept for 2 of 5 secs (signal 2)
Sleeping for 3
Slept for 3 of 5 secs (signal 2)
Sleeping for 2
Slept for 4 of 5 secs (signal 2)
Sleeping for 1