I have a small program that needs to be run in a small Linux embedded system (ARM). It is written in C. It needs to poll some data (2x64-bit) from an API provided by the system manufacturer, and then do some calculations and send the data through the network. The data should be polled around 30 times every second (30Hz).
What would be the best way to do it in C? I've seen solutions using sleep(), but it does not seem to be the best option for the job.
I suggest consider using the poll(2) multiplexing syscall to do the polling.
notice that when poll is waiting and polling for input, it does not consume any CPU
If the processing of each event takes some significant time (e.g. a millisecond or more) you may want to recompute the delay.
You could use timerfd_create(2) (and give both your device file descriptor and your timer fd to poll). See also timer_create(2)...
Perhaps clock_gettime(2) could be useful.
And reading time(7) is definitely useful. Perhaps also the Advanced Linux Programming book.
sleep() suspends execution in seconds, if you are looking for a more accurate sleep()-like function, use usleep() which suspends execution in microseconds, or nanosleep() in nanoseconds.
Related
I am doing C program in Linux . I have a main thread which continuously updates values of two variables and other thread write those variable values into a file every 20 milliseconds. I have used usleep to achieve this time interval. sample code is below.
main()
{
.
.
.
.
.
pthread_create(...write_file..); /* started another thread by passing a function write_file */
while(variable1)
{
updates value of variables
}
return 0;
}
void write_file()
{
.
.
.
.
fp = fopen("sample.txt" , "a");
while(variable2)
{
fprintf(fp," %d \n", somevariable);
usleep(20 * 1000);
}
fclose(fp);
}
Is it suitable to use usleep function achieve 20 milliseconds time interval or should I use some other methods like Timer.?
Is this usleep is accurate enough ? Does this sleep function any way affect the main thread ?
Using of sleep() family often results in non-precise timing, especially when process has many CPU-consuming threads and required intervals are relatively small, like 20ms. So you shouldn't assume that *sleep() call blocks execution exactly to specified time. For described above situation actual sleep duration may be even twice or more greater than specified (assuming that kernel is not real-time one). As result you should implement some kind of compensation logic, that adjusts sleep duration for subsequent calls.
More precise (but of course not ideal) approach is to use POSIX timers. See timer_create(). The most precise timers are the ones that use SIGEV_SIGNAL or SIGEV_THREAD_ID notifications (latter is only on Linux systems). As signal number you can use one of the real-time signals (SIGRTMIN to SIGRTMAX), but be aware that pthread implementations often use few of these signals internally, so you should choose actual number carefully. And also doing something in signal handler context requires extra attention, because not every library function may be used safely here. You can find safe list here.
P.S. Also note that select() called with empty sets is a fairly portable way to sleep with subsecond precision.
Sleeping: sleep() and usleep()
Now, let me start with the easier timing calls. For delays of multiple seconds, your best bet is probably to use sleep(). For delays of at least tens of milliseconds (about 10 ms seems to be the minimum delay), usleep() should work. These functions give the CPU to other processes (``sleep''), so CPU time isn't wasted. See the manual pages sleep(3) and usleep(3) for details.
For delays of under about 50 milliseconds (depending on the speed of your processor and machine, and the system load), giving up the CPU takes too much time, because the Linux scheduler (for the x86 architecture) usually takes at least about 10-30 milliseconds before it returns control to your process. Due to this, in small delays, usleep(3) usually delays somewhat more than the amount that you specify in the parameters, and at least about 10 ms.
nanosleep()
In the 2.0.x series of Linux kernels, there is a new system call, nanosleep() (see the nanosleep(2) manual page), that allows you to sleep or delay for short times (a few microseconds or more).
For delays <= 2 ms, if (and only if) your process is set to soft real time scheduling (using sched_setscheduler()), nanosleep() uses a busy loop; otherwise it sleeps, just like usleep().
The busy loop uses udelay() (an internal kernel function used by many kernel drivers), and the length of the loop is calculated using the BogoMips value (the speed of this kind of busy loop is one of the things that BogoMips measures accurately). See /usr/include/asm/delay.h) for details on how it works.
Source: http://tldp.org/HOWTO/IO-Port-Programming-4.html
Try use nanosleep() instead usleep(), it should be more accurately for 20ms interval.
I would like to measure the ping time between a sender process and a consumer.
Both processes run on the same physical host, Linux 64 bit.
I'm currently using clock_gettime(CLOCK_REALTIME, &cur_ts);.
I basically capture the current timestamp cur_ts and send it to consumer process; as soon as it's being received on the other end I then invoke clock_gettime(CLOCK_REALTIME, &cur_ts); again in the second process and subtract the two times.
Is this procedure accurate to measure ping between two processes? Should I be using something different?
Thanks
Yes
You are using the correct interface. This is a Posix-specified HRT (High Resolution Timer) that is available in modern Loonix, and your use is the canonical standard.
For ping resolutions it probably doesn't matter, but it's possible to use CLOCK_MONOTONIC, especially for short intervals. Under other conditions, CLOCK_REALTIME may be more accurate. However, the exact meaning of these clocks is not specified by Posix, and on Linux, I believe all of them are subject to NTP adjustments. That's a good thing for long intervals, at least.
On Linux, to get access to the underlying hardware clock without NTP adjustments, you have to go off the Posix reservation and use CLOCK_MONOTONIC_RAW.
http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_gettime.html
In a long-running server program (built in C) in a Posix (Linux) environment: what is the best approach to get a function to execute at a specific time in the future? It doesn't need to execute in any particular thread, but the accuracy of the execution time needs to be a few milliseconds. General approaches or specific code is appreciated.
There are some high resolution clock functions in the GNU C library (sys/timex.h), so although they are not POSIX, they will be portable linux wise.
High Accuracy Clock -- The GNU C Library
Those functions are prefixed 'ntp' although they do not require or make use of any ntp service, so the relationship is purely superficial.
Beware that although the granularity is in microseconds, the linux kernel has a userspace latency of 10ms so don't bother or expect anything more accurate than that.
Once you have the current high resolution time, you could then calculate a duration and use (posix) nanosleep (but again, round to 10ms) to set a delay. There is also a clock_nanosleep which might be of interest.
You should look up posix timers. It gives you a simple interface to scheduling future work. You can manage it to send you a signal in x seconds/ nanoseconds (ad then you can put your function as it's signal handler). Lookup timer_create
So I have an embedded Linux device that is connected to a motor controller via a serial port. I am writing an interface library which makes a lot of nice generic functions which other programs will call. One of which is a function to run the program that is currently on the controller's flash disk:
int run_motor_program(int serial_fd, char *label, timeout);
The general pseudocode for this function is:
call write(serial_fd, "start program at `label`")
perform a couple read()'s / write()'s to check whether program has started on the motor controller
do
/* some stuff */
while(program is running AND timeout hasn't exceeded)
If the timeout exceeded, kill motor and return timeout error
The timeout in the above function definition is used in case something goes wrong while running the program on the motor controller. If the motor controller gets stuck in a longer loop than expected, I need the ability to stop program.
The only ways I know for keeping track of a timeout are:
1) Calling gettimeofday() before and during the loop to see if elapsed time is > timeout value passed in
2) Calling clock_gettime() and basically doing the same as 1.
3) Using timer_create() before the loop and timer_getoverrun() in the loop to check if the time has elapsed (this seems to be the most elegant solution, but I can't seem to get timer_getoverrun() to work with SIGEV_NONE [I don't want to use signals]).
Which of these (or if anyone has any other suggestions) is the best way to handle including a timeout in a function? I really only need resolution down to the millisecond.
I tend to do option 1 myself. If subsecond granularity isn't needed, then I'll use time. Typically the work is checking for IO, so I also use a select with a timeout configured.
You could consider using one of the alarm signal mechanisms. The simplest and oldest is alarm(), which schedules a SIGALRM signal after the specified number of seconds. If you have a signal handler for SIGALRM, your process won't die but will allow you to recover from the error.
The primary limitation of alarm() is that it deals in whole seconds. There are a plethora of sub-second or fractional second alternatives. You should look at setitimer(). You might use nanosleep() but you'd probably also need to use threads since nanosleep() blocks the calling thread. That moves it up the complexity scale. There are calls like pthread_cond_timedwait() that could also be used in a threaded program.
Your prototype int run_motor_program(int serial_fd, char *label, timeout); won't compile; you need to define the type of the timeout argument. You also need to decide what your argument means - whether it is an interval or duration of time (the number of seconds to run the motor for before timing out) or whether it is the end time (the Unix time after which the program must be stopped). There are various sub-second structures that you'll have to negotiate. Your choice is likely to be affected by which system call you use for implementing the timeout.
I'm trying simulate a key down and key up action.
For example: 2638 millseconds.
SendMessage(hWnd, WM_KEYDOWN, keyCode, 0);
Sleep(2638);
SendMessage(hWnd, WM_KEYUP, keyCode, 0);
How would you know if it really worked?
You wouldn't with this code, since accurately measuring the time that code takes to execute is a difficult task.
To get to the question posed by your question title (you should really ask one question at a time...) the accuracy of said functions is dictated by the operating system. On Linux, the system clock granularity is 10ms, so timed process suspension via nanosleep() is only guaranteed to be accurate to 10ms, and even then it's not guaranteed to sleep for exactly the time you specify. (See below.)
On Windows, the clock granularity can be changed to accommodate power management needs (e.g. decrease the granularity to conserve battery power). See MSDN's documentation on the Sleep function.
Note that with Sleep()/nanosleep(), the OS only guarantees that the process suspension will last for at least as long as you specify. The execution of other processes can always delay resumption of your process.
Therefore, the key-up event sent by your code above will be sent at least 2.638 seconds later than the key-down event, and not a millisecond sooner. But it would be possible for the event to be sent 2.7, 2.8, or even 3 seconds later. (Or much later if a realtime process grabbed hold of the CPU and didn't relinquish control for some time.)
Sleep works in terms of the standard Windows thread scheduling. It is accurate up to about 20-50 milliseconds.
So that it's ok for user experience-dependent things. However it's absolutely inappropriate for real-time things.
Beside of this, there're much better ways to simulate keyboard/mouse events. Please see SendInput.
The sleep() function will return before the desired delay when the requested delay is shorter than the time left until the next interrupt occurs. But this only points out that you want to sleep for a shorter period of time than currently is supported by your system. It is advisable to setup the multimedia timer resource to a higher interrupt frequency to obtain better matching of the observed sleep delay with respect to the desired delay.
The the comments in the following threads:
How to get an accurate 1ms Timer Tick under WinXP
Sleep Less Than One Millisecond
The command Sleep() will ensure that thread is suspended at least the amount of time which is given as argument. Operating system does not guarantee it. For detailed discussion you can refer the below post
how is sleep implemented at OS level?