Timer interrupt in C - c

I have to write a c file which is about timer interrupt.Program will run on DosBox.
Features of program is simple :
Program call a function(which is typed by me) for each timer interrupts.And these interrupts will be programmed with setvect and getvect functions.
For example It would be very nice if I have a c code which prints "Hello world\n" to screen once in a second without any sleep or delay function.I mean the code that print "hello world" must be in a function and for each interrupt program must call this function.
It is very hard to find example of this case,Can you forward any example link ? Thanks for all help..

#include<signal.h>
#include<sys/time.h>
#include <unistd.h>
#include <assert.h>
#include <stdio.h>
#define PERIOD 999999
static sigset_t block ;
void timer_handler ();
static void init( ) __attribute__((constructor));
void init(){
sigemptyset(&block);
sigaddset(&block,SIGVTALRM);
struct sigaction act={0};
struct timeval interval;
struct itimerval period;
act.sa_handler=timer_handler;
assert(sigaction(SIGVTALRM,&act,NULL)==0);
interval.tv_sec=0;
interval.tv_usec=PERIOD;
period.it_interval=interval;
period.it_value=interval;
setitimer(ITIMER_VIRTUAL,&period,NULL);
}
void timer_handler(int sig){
write(1,"Hi\n",3);
}
int main(){
while(1);
return 0;
}

Just an advice.
In general, it is a good thing not to use function like print in interruption. In your case, because your code is simple it's not really a problem but you can have some priorities issues on more complexe programs if you spend to much time in interruptions...

Related

Sleep() function in C not working on hp non-stop

I am trying something in C on hp-nonstop(tandem),
As part my task is to wait for sometime.
I try to use the
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
printf("Something");
sleep(5);
printf("Something");
fflush(stdout);
}
}
It's compiling without any problem,
While running it is giving ABENDED: each time different no.
The result calling sleep() from guardian environment is undefined. That might be leading to ABEND that you mentioned. If you want to wait for some time in guardian hp-nonstop environment, you should call DELAY(). It takes centi-seconds as arguments. So if you want to add delay of 5 seconds, you should call it as DELAY (500). You also need to include the header #include<cextdecs(DELAY)>

Sleep | warning implicit declaration of function `sleep'?

I am learning C.
In this program
I use sleep function to slowdown a count down.
My text book doesn't specify a library I should include to use the sleep function.
So I use it without including any special library for it and it works.
But it gives me this warning message in codeblocks.
I tried to include <windows.h> but still the same warning message appears.
warning D:\Project\C language\trial8\trial8.c|19|warning: implicit
declaration of function `sleep'|
And here is my code.
#include <stdio.h>
int main()
{
int start;
do
{
printf("Please enter the number to start\n");
printf("the countdown (1 to 100):");
scanf("%d",&start);
}
while(start<1 || start>100);
do
{
printf("T-minus %d\n",start);
start--;
sleep(3000);
}
while(start>0);
printf("Zero!\n Go!\n");
return(0);
}
I want to know what does the warning message mean? How important is it? Is there anything that I should do about it? Note that the program works anyway.
The issue is in the libraries (header files):
on Windows:
#include <windows.h> and Sleep(1000); => 1000 milliseconds
on Linux:
#include <unistd.h> and sleep(1); => 1 second
The function sleep is not part of C programming language. So, C compiler needs a declaration/prototype of it so that it can get to know about about number of arguments and their data types and return data type of the function. When it doesn't find it, it creates an Implicit Declaration of that function.
In Linux, sleep has a prototype in <unistd.h> and in windows, there is another function Sleep which has a prototype in <windows.h> or <synchapi.h>.
You can always get away with including header, if you explicitly supply the prototype of the function before using it. It is useful when you need only few functions from a header file.
The prototype of Sleep function in C on windows is:
VOID WINAPI Sleep(_In_ DWORD dwMilliseconds);
Remember, it is always a good practice to supply the prototype of the function being used either by including the appropriate header file or by explicitly writing it. Even, if you don't supply it, compiler will just throw a warning most of the time and it will make an assumption which in most cases will be something that you don't want. It is better to include the header file as API might change in future versions of the Library.
Windows doesn't have the sleep function. Instead, it has Sleep, which takes the number of milliseconds to sleep:
VOID WINAPI Sleep(
_In_ DWORD dwMilliseconds
);
You'll need to either #include <windows.h> or #include <synchapi.h>, depending on the version of Windows you're running. See MSDN for more details.
Update in 2022:
As it is stated on the Linux man page here we need to include unistd.h and should do fine for all OS.
#include <stdio.h>
#include <unistd.h>
int main()
{
sleep(1); /* sleep for 1 second*/
printf("END\n");
return 0;
}
To make it more cross-platform, try this:
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif

What is the proper #include for the function 'sleep()'?

I am using the Big Nerd Ranch book Objective-C Programming, and it starts out by having us write in C in the first few chapters. In one of my programs it has me create, I use the sleep function. In the book it told me to put #include <stdlib.h> under the #include <stdio.h> part. This is supposed to get rid of the warning that says "Implicit declaration of function 'sleep' is invalid in C99". But for some reason after I put #include <stdlib.h>, the warning does not go away.. This problem does not stop the program from running fine, but I was just curious on which #include I needed to use!
The sleep man page says it is declared in <unistd.h>.
Synopsis:
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
sleep is a non-standard function.
On UNIX, you shall include <unistd.h>.
On MS-Windows, Sleep is rather from <windows.h>.
In every case, check the documentation.
this is what I use for a cross-platform code:
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
int main()
{
pollingDelay = 100
//do stuff
//sleep:
#ifdef _WIN32
Sleep(pollingDelay);
#else
usleep(pollingDelay*1000); /* sleep for 100 milliSeconds */
#endif
//do stuff again
return 0;
}
What is the proper #include for the function 'sleep()'?
sleep() isn't Standard C, but POSIX so it should be:
#include <unistd.h>
sleep(3) is in unistd.h, not stdlib.h. Type man 3 sleep on your command line to confirm for your machine, but I presume you're on a Mac since you're learning Objective-C, and on a Mac, you need unistd.h.
Given that sleep is a non-standard function, I created a sleep function with the standard library time.h
#include <time.h>
void sleep(double s) {
time_t cur_time = time(NULL);
while ((difftime(time(NULL), cur_time)) < s);
}

pthread_cancel don't work under solaris

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
char a[]="Hello";
void * thread_body(void * param) {
while(1)
printf("%s\n", param);
}
int main(int argc, char *argv[]) {
pthread_t threadHello;
int code;
pthread_create(&threadHello, NULL, thread_body, a);
pthread_cancel(threadHello);
pthread_exit(0);
}
When I compile and run this under Solaris 10 (SunOS 5.10), it doesn't stop. But under Linux it works as intended.
Per POSIX, printf (and all of stdio) may be a cancellation point. It is not required to be. I suspect Solaris just doesn't choose to make it one. Have you tried another function like sleep here?
If you really need printf to be cancellable, you'll probably need to implement your own printf-like function as a wrapper for dprintf, but that won't work so well if you're depending on the builtin locking functionality of stdio..

How to use timers in Linux kernel device drivers?

I want to implement a counter in Linux device drivers which increments after every fixed interval of time. I want to do this with the help of timers. A sample code snippet would be very useful.
Have a look at following article IBM Developerworks: Timers and Lists
There is a small example of how to use Linux kernel timers (included it here for convenience, comments are from myself, removed printk messages)
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/timer.h>
MODULE_LICENSE("GPL");
static struct timer_list my_timer;
void my_timer_callback( unsigned long data )
{
/* do your timer stuff here */
}
int init_module(void)
{
/* setup your timer to call my_timer_callback */
setup_timer(&my_timer, my_timer_callback, 0);
/* setup timer interval to 200 msecs */
mod_timer(&my_timer, jiffies + msecs_to_jiffies(200));
return 0;
}
void cleanup_module(void)
{
/* remove kernel timer when unloading module */
del_timer(&my_timer);
return;
}
Around Linux kernel 4.15 release, void setup_timer(timer, function, data); became obsolete with an intent to remove it completely.
Instead, now we have to use
void timer_setup(
struct timer_list *timer,
void (*callback)(struct timer_list *),
unsigned int flags
);
This can be found in linux/timer.h file.
Here's a full example of module_with_timer.c
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/jiffies.h>
#include <linux/timer.h>
MODULE_LICENSE("GPL");
static struct timer_list my_timer;
void my_timer_callback(struct timer_list *timer) {
printk(KERN_ALERT "This line is printed after 5 seconds.\n");
}
static int init_module_with_timer(void) {
printk(KERN_ALERT "Initializing a module with timer.\n");
/* Setup the timer for initial use. Look in linux/timer.h for this function */
timer_setup(&my_timer, my_timer_callback, 0);
mod_timer(&my_timer, jiffies + msecs_to_jiffies(5000));
return 0;
}
static void exit_module_with_timer(void) {
printk(KERN_ALERT "Goodbye, cruel world!\n");
del_timer(&my_timer);
}
module_init(init_module_with_timer);
module_exit(exit_module_with_timer);
And the Makefile is
obj-m = module_with_timer.o
# Get the current kernel version number
KVERSION = $(shell uname -r)
all:
make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean
Note: In real life programming, it is better to check the version of the kernel we are compiling for and then use an then appropriately start the timer.
References:
https://lwn.net/Articles/735887/
Depending on what you exactly want to do, you can directly use jiffies to measure time, as it has been suggested in the comments. You can also use kernel timers, and given the information in your question, they seem to be a better fit.
The kernel timers API is quite intuitive:
#include <linux/timer.h>
struct timer_list {
/* ... */
unsigned long expires;
void (*function)(unsigned long);
unsigned long data;
};
void init_timer(struct timer_list *timer);
struct timer_list TIMER_INITIALIZER(_function, _expires, _data);
void add_timer(struct timer_list * timer);
int del_timer(struct timer_list * timer);
So you would just need to define a timer function and then initialize and start the timer.
You have several sources to further learn about this topic:
Understanding the Linux Kernel. This book is a sort of bible for the kernel. It is somehow outdated in some areas, but still a really good source of information.
Linux Device Drivers. This is a very useful book when developing device drivers. There is an online version too here. The chapter dealing with time, timers, etc. is chapter 7. This book may be also a bit outdated since it is from 2005 too.
Linux Kernel Development. I have not checked this book, but the good point is that it is much newer (from 2010), so you may find some updated information compared to the previous two books.

Resources