Home / setitimer

UNIX/linux のインターバル・タイマーは、シグナルが送られる訳だが、ITIMER_VIRTUAL を使う場合、下のように何もしないで待つのはプロセスが実行されていないから駄目である。
2行のコメントアウトへ替えないといけない(暫し考えてしまった)。

成る程、ご尤もな仕様ではある。
裏を返せば、プロセスが実行した時間でもって知らせてくれる訳で、それはそれで適する場合がありそうだ。

/*
 * g++ hoge.cc -o hoge
 */

#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>

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


static pid_t pid;

void handler(int)
{
    printf("time up!\n");
    fflush(stdout);

    if (pid != 0)
        kill(pid, SIGKILL);

    return;
}

int main(int argc, char* argv[])
{
    int tm = 10;
    if (argc >= 2)
        tm = strtol(argv[1], NULL, 10);

    
    pid = fork();
    if (pid == 0)
    {
        printf("%d\n", getpid());
        sleep(tm);
        exit(0);
    }

    /*if (signal(SIGALRM, handler) == SIG_ERR)*/
    if (signal(SIGVTALRM, handler) == SIG_ERR)
        perror("signal error");

    struct itimerval tv = { 0, 0,
                            5, 0 };

    /*if (setitimer(ITIMER_REAL, &tv, NULL) < 0)*/
    if (setitimer(ITIMER_VIRTUAL, &tv, NULL) < 0)
        printf("setitimer error\n");

    wait(NULL);     /* 子の変化を待つ。*/

    printf("done\n");
    exit(0);
}

Home / setitimer

© 2008 usskim    http://usskim.web.fc2.com/
inserted by FC2 system