在C中睡觉时留下时间

时间:2013-10-25 22:49:24

标签: c operating-system

我想编写一个程序来打印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);

}

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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))