timer in C
I'm teaching myself C and i'm wondering how to implement something like Java's sleep function so i can make something happen every second or so. For example like a simple spinner of ascii that uses \ | / - in it and switches characters every second. I'm thinking it is in the time.h but I haven't seen how to do implement that.
:Pengy: |
nanosleep or sleep will work for you. nanosleep runs on nanoseconds and sleep runs on seconds.
nanosleep: Code:
SYNOPSIS Code:
SLEEP(3) Linux Programmer's Manual SLEEP(3) |
#include <signal.h>
#include <unistd.h> /* */ void tick(int i); /* */ void setAlarm(int delay) { signal(SIGALRM, tick); } /* */ void tick(int i) { printf(" } |
#include <signal.h>
#include <unistd.h> /* */ void tick(int i); /* */ void setAlarm(int delay) { signal(SIGALRM, tick); } /* */ void tick(int i) { static nr = 0; printf(" tick tack tock: nr %d\n", nr++); } |
#include <signal.h>
#include <unistd.h> /* */ void tick(int i); /* */ void setAlarm(int delay) { signal(SIGALRM, tick); } /* */ void tick(int i) { static nr = 0; printf(" tick tack tock: nr %d\n", nr++); setAlarm(5); } int main(int argc, char** argv) { setAlarm(5); /* do something that .. does something here .. like a sleep*/ sleep(60); return 0; } ...................... And yes, I have no clue how to make this a code section.. and I think theres a autosubmit thing.. I hate that.. loses focus.. and blamm.. submitted. |
you can put your code inside code tags:
[ code ] code inside here [ /code ] no spaces before or after the "[" and "]" though. there's a button on the posting page too labeled PHP, but it looks like a single line entry field. |
Okay, here is what I have so far. It works without the sleep(). Now I just need to get the sleep to work correctly. any ideas?
Code:
#include <stdio.h> |
sleep(60);
Will make it so that you have to wait a full minute between baton movements. Code:
for (i = 0; i < 5; i++) { |
ok, this is what I ended up with and it works perfectly. The thing that helped was flushing stdout. I didn't know about that and not doing that was causing nothing to appear. Thanks for the info!!!
Code:
#include <stdio.h> |
Just a side question: What's the syntax to use the nanosecond function in there?
|
#include <time.h>
int nanosleep(const struct timespec *req, struct timespec *rem); |
All times are GMT -5. The time now is 09:21 AM. |