timer를 사용해서 1초에 값 증가시키는 법 가르쳐 주세요~

leo~~~~의 이미지

int i; 라는 변수의 초기 값이 1이고
timer를 사용해서 1초에 1씩
i의 값을 증가 시키려고 하는데요
어떻게 해야 할까요...
어려운거 같지는 않은데....
찾지를 못하겠네요....
부탁드립니다~

hie의 이미지

#include <linux/timer.h>
init_time(...)
add_timer(..)

상기 함수를 이용하세요.

서지훈의 이미지

      1 #include <stdio.h>
      2 #include <time.h>
      3 
      4 
      5 int main(int argc, char **argv)
      6 {
      7     time_t  i, ttt;
      8 
      9 
     10     time(&i);
     11 
     12     sleep(2);
     13 
     14     time(&ttt);
     15 
     16     printf("i = [%u], ttt = [%u], res = [%d]\n", i, ttt, ttt - i);
     17 
     18 
     19     return 0;
     20 }

위와 같이 기준 시간(처음 시작 시간: i)과 비교할 시간(경과 시간: ttt)의 차이값으로 원하는 값을 얻을 수가 있지 않을까요?
이렇게 하지 않고 timer(signal처리가 필요함)가 들어갈 경우 아주 복잡해 지지 않을지 ?

<어떠한 역경에도 굴하지 않는 '하양 지훈'>

#include <com.h> <C2H5OH.h> <woman.h>
do { if (com) hacking(); if (money) drinking(); if (women) loving(); } while (1);

leo~~~~의 이미지

'sleep' : undeclared identifier

이렇게 sleep이 선언 안됐다고 나와요...ㅡㅡ

서지훈의 이미지

sleep()은 사용하실 필요 없습니다.
그냥 예를 든것 입니다.
참고로 man sleep 하시면 필요한 include 파일이 나옵니다.

<어떠한 역경에도 굴하지 않는 '하양 지훈'>

#include <com.h> <C2H5OH.h> <woman.h>
do { if (com) hacking(); if (money) drinking(); if (women) loving(); } while (1);

익명 사용자의 이미지

#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <errno.h>

int g_count;

// 아래 함수는 커널이 불러주는 함수다. 
// 주기적으로 타이머 시그널이 발생시에 불러준다.
// 그냥 타이머시그널 핸들러라고 부른다.
void periodicTimerHandler (int signum)
{
   static int count = 0;

   printf ("[%s:%ld:%s]timer expired %d times\n", 
            __FILE__,(long) __LINE__, __func__, ++count);
   g_count++;
}

void initTimer(float standby, float timeout)
{
   struct sigaction sa;
   struct itimerval timer;
   long sec, usec;
   long s_sec, s_usec;
   if ( standby <= 0 ) {
      printf("invalid timeout value %f\n", timeout);
      return ;
   }
   s_sec = (long)standby;
   s_usec = (long)((standby - s_sec)*1000000);

   if ( timeout <= 0 ) {
      printf("invalid timeout value %f\n", timeout);
      return ;
   }
   sec = (long)timeout;
   usec = (long)((timeout - sec)*1000000);
   // timer 핸들러를 등록 SIGALRM.
   memset (&sa, 0, sizeof (sa));
   sa.sa_handler = &periodicTimerHandler;

   sigaction (SIGALRM, &sa, NULL);

   // 타이머 시작시기 stand by....   timer.it_value.tv_sec = s_sec;
   timer.it_value.tv_usec = s_usec;

   // 주기적으로 동작
   timer.it_interval.tv_sec = sec;
   timer.it_interval.tv_usec = usec;
   setitimer (ITIMER_REAL, &timer, NULL);
   printf(" %f 초 후부터, 매 %f초 간격으로 타이머가 동작합니다\n", standby, timeout);
}

int main ()
{

   char buf[1024];
   int  ret;

   // 출력이 printf()와 write()를 둘다 사용해서리, 출력이 뒤섞이게 됨으로
   // stdout을 버퍼링없이 사용.
   // 즉, printf()와 write(1,.....)이 거의 동급으로 동작
   setvbuf (stdout, NULL, _IONBF, 0);

   // 타이머는 10초 후부터 매 0.5초 간격으로 발생
   initTimer( 10,0.5 );

   /* Do busy work. */
   while (1) {

      ret = read(0, buf, 1024); // 보통 입력이 있거나,
                                // 0번 장치(입력파일)에 문제시 함수리턴
      if ( ret <= 0 ) {
         if (errno == EINTR ) { // 그러나, 임의의 signal이 뜨면 리턴함.
                              // read()만이 아니고, 모든 블록킹 시스템호출이
                              // 그렇게 동작함
            printf("시그널이 떠서 read()에서 탈출... 그래서 재시도..\n");
            continue;
         }
         else {
            printf("read() error\n");   
            exit(0);
         }
      }
      else {
         printf("global count = %ld\n", g_count);
         printf("read() return %d\nval = [", ret);
         write(1, buf, ret);
         printf("]\n", ret);
      }
   }
}
익명 사용자의 이미지

initTimer()함수와 periodicTimerHandler() 이 두개를 잘 보면 기본 목적이야 되겠지만, 시그널에 따른 블록킹 시스템호출의 탈출을 고려하지 않는다면(이런거 고려안하고 짜서 파는 프로그램도 여럿봤습니다),
가끔....어쩌다가.... 잘 안도는 :twisted: ... 좋은. :twisted: .. 프로그램을 만들 수 있습니다. :twisted:

익명 사용자의 이미지

Quote:
// 타이머 시작시기 stand by.... timer.it_value.tv_sec = s_sec;


Quote:
// 타이머 시작시기 stand by....
timer.it_value.tv_sec = s_sec;

되어야 맞습니다.. 죄송합니다.
tinywolf의 이미지

오옷 상세한 예제..

ㅡ_ㅡ;

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.