0

我想编写一个程序来打印 sleep() 函数期间的睡眠时间,这不起作用,因为它只在唤醒后打印。

睡觉时怎么打印?我必须使用并发吗?

#include <unistd.h>
#include <stdio.h>

unsigned int snooze(unsigned int secs);


unsigned int snooze(unsigned int secs){
  unsigned int timeleft = sleep(secs);
  printf("Slept for %d of %d secs\n", secs - timeleft, secs);
  return timeleft;
}


int main(int argc, char*argv[]){
  snooze(5);

}
4

2 回答 2

2

如果您有一些将向它发送信号的代码,那么您代码上的这个变体(我称之为它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
于 2013-10-26T04:31:32.663 回答
0

如果您想定期醒来并注意您还剩多少睡眠时间,您可以执行以下操作:

void snooze(unsigned int secs)
{
    time_t start = time(NULL);
    while(time(NULL) < start+secs)
    {
        sleep(1);
        int elapsed = time(NULL)-start;
        printf("Slept for %d of %d secs\n", elapsed, secs);
    }
}

就个人而言,我不认为这种方法是一种非常宁静的睡眠方式。:-)

如果您只是想防止过早醒来,您可以将 更改sleep(1)sleep((start+secs)-time(NULL)),我想。

于 2013-10-26T02:03:53.060 回答