Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I'm looking for an open source timer library written in C. The library should have Timer callback functions, etc.
On searching I see POSIX timers or setitimer(), which use a signal based approach that may lead to problems in multithreaded code.
Say if I use POSIX Timers inside threaded code, the signals won't be reaching to the correct place. If I use several timers in a process then each one should use different signals. Are there any other alternatives?
Since you are running Linux, I would recommend using the built in POSIX timer API's.
int timer_create(clockid_t clockid, struct sigevent *sevp, timer_t *timerid);
Here is a link to some documentation showing how to use POSIX timers which provide support for callback functions.
Regarding multiple timers in a process, the documentation says this:
A program may create multiple interval timers using timer_create().
Timers are not inherited by the child of a fork(2), and are disarmed and
deleted during an execve(2).
The kernel preallocates a "queued real-time signal" for each timer created
using timer_create(). Consequently, the number of timers is limited by the
RLIMIT_SIGPENDING resource limit (see setrlimit(2)).
Note that POSIX timers can be used in a threaded application by setting up notification using SIGEV_THREAD_ID as shown below:
The sevp.sigev_notify field can have the following values:
SIGEV_NONE
Don't asynchronously notify when the timer expires. Progress of the
timer can be monitored using timer_gettime(2).
SIGEV_SIGNAL
Upon timer expiration, generate the signal sigev_signo for the process.
See sigevent(7) for general details. The si_code field of the
siginfo_t structure will be set to SI_TIMER. At any point in time, at
most one signal is queued to the process for a given timer; see
timer_getoverrun(2) for more details.
SIGEV_THREAD
Upon timer expiration, invoke sigev_notify_function as if it were the
start function of a new thread. See sigevent(7) for details.
SIGEV_THREAD_ID (Linux-specific)
As for SIGEV_SIGNAL, but the signal is targeted at the thread whose ID
is given in sigev_notify_thread_id, which must be a thread in the same
process as the caller. The sigev_notify_thread_id field specifies a
kernel thread ID, that is, the value returned by clone(2) or gettid(2).
This flag is only intended for use by threading libraries.
The Linux way of doing it would be via timerfd_create which integrates nicely with epoll-based event loops (and thereby avoiding the restrictions of signal handlers)
This is far to simple to create a library for.
example:
#include <time.h>
int main()
{
time_t start,end;
double dif;
double duration=40f; //duration of timer
bool loop=true;
while(loop==true)
{
time(&start);
if(dif==duration)
{
/*callback*/
dif=0;
}
//do stuff
time(&end);
dif+=difftime(end,start);
}
{
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
I know that exec should replace the entire process image, but I also know that some things like file descriptors are preserved upon a call to one of the exec-family functions.
On what basis are aspects of the environment kept upon a call to execve()?
From execve(3):
All process attributes are preserved during an execve(), except the
following:
The dispositions of any signals that are being caught are reset
to the default (signal(7)).
Any alternate signal stack is not preserved (sigaltstack(2)).
Memory mappings are not preserved (mmap(2)).
Attached System V shared memory segments are detached
(shmat(2)).
POSIX shared memory regions are unmapped (shm_open(3)).
Open POSIX message queue descriptors are closed
(mq_overview(7)).
Any open POSIX named semaphores are closed (sem_overview(7)).
POSIX timers are not preserved (timer_create(2)).
Any open directory streams are closed (opendir(3)).
Memory locks are not preserved (mlock(2), mlockall(2)).
Exit handlers are not preserved (atexit(3), on_exit(3)).
The floating-point environment is reset to the default (see
fenv(3)).
POSIX also mandates this (although negated):
The new process shall inherit at least the following attributes from
the calling process image:
Nice value (see nice())
semadj values (see semop())
Process ID
Parent process ID
Process group ID
Session membership
Real user ID
Real group ID
Supplementary group IDs
Time left until an alarm clock signal (see alarm())
Current working directory
Root directory
File mode creation mask (see umask())
File size limit (see getrlimit() and setrlimit())
Process signal mask (see pthread_sigmask())
Pending signal (see sigpending())
tms_utime, tms_stime, tms_cutime, and tms_cstime (see times())
Resource limits
Controlling terminal
Interval timers
The initial thread of the new process shall inherit at least the
following attributes from the calling thread:
Signal mask (see sigprocmask() and pthread_sigmask())
Pending signals (see sigpending())
All other process attributes defined in this volume of POSIX.1-2017
shall be inherited in the new process image from the old process
image. All other thread attributes defined in this volume of
POSIX.1-2017 shall be inherited in the initial thread in the new
process image from the calling thread in the old process image. The
inheritance of process or thread attributes not defined by this volume
of POSIX.1-2017 is implementation-defined.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I need to do some operation at regular intervals in my thread. What is the best method to do this?
Like if, i have a local socket communication between linux deamon and a android application. In this case, if i want to send data periodically to the android app from deamon, how can i proceed?
If you use Linux why not try sleep() or usleep() functions of unistd.h?
sleep(5);
Will pause the thread for five seconds and then resume execution.
sleep(sec)
The sleep() function shall cause the calling thread to be suspended from execution until either the number of realtime seconds specified by the argument seconds has elapsed or a signal is delivered to the calling thread and its action is to invoke a signal-catching function or to terminate the process.
usleep(usec)
usleep() function suspends execution of the calling thread for (at least) usec microseconds.
Emphasis mine.
Taken from here and here.
You should use Simple Signals - C programming and alarm function if you want truely accurate timing. If you don't do this, using sleep() etc will eventually result in your timer shifting due to the overhead of your code, the OS, etc.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
What is a practical relevance of signals in C programs ?
Where do we need signals. I am getting confused and feeling traped in this topic, Who generates signals ?
Signals are a lightweight way for processes to communicate with each other asynchronously; as such, it shouldn't be a surprise that processes generate signals.
Signals are in C because signals were how you communicated with a process in the original version of UNIX.
They are a fairly simple way of allowing your process to respond to external requests such as "re-read my config file", for example.
The K&R chapter is a good intro, but read the C standard to see the minimum for what is defined. In particular, the only portable thing you can do in a signal handler is either abort the process, or set an atomic flag which your main thread of execution will check in due course. In practice, people do more complicated things in signal handlers such as making system calls.
Signals provide a way of supporting asynchronous interrupts in a C program. That said, the C spec is almost completely void of specified behavior for signals, leaving them essentially entirely up to the implementation, so writing portable code that uses signals is almost impossible. You need to carefully read the documentation for your implementation to see what exactly signals can do.
I'm building two static c libraries. Each of the libraries have a routine that needs to run once every second after calling mylib_init();
I implemented this in each library using setitimer, which uses the ITIMER_REAL resource and the SIGALRM signal.
void Start1msTimer()
{
struct itimerval new;
memset(&new,0, sizeof(new));
new.it_interval.tv_sec=1;
new.it_value.tv_sec=1;
signal (SIGALRM, OneSecTimeout);
setitimer (ITIMER_REAL, &new,NULL);
}
Ok so far so good everything was working.
Now I'm building a sample application that uses both of these libraries, and conflicts are arising. I have realized an application can only have one handler for each signal, and ITIMER_REAL can only be used for one timer, not both. So obviously things are not working now.
What would be a better way for me to implement the timing in each of my libraries?
In general, is it a bad idea to have any signal handlers inside of a library?
Yes, it's a very bad idea to "use up" application-level resources in a library, since the application developer using the library won't get a say in how the resources should be allocated.
And, as you discovered, you get interoperability problems when multiple libraries want to own the same resource.
One way to fix this is to factor out the requirement, have a function mylib_update() and document that the application must call it once a second. That leaves the question of how to implement such a timer-based updating to the application, where it belongs.
You could use threads + a syncronization method. Instead of writing a signal handler, you write a thread. Using a semaphore, you can even run your event thread either on timeout or on demand (ie the app calls a library function that post the semaphore).
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Bind threads to processors
In Linux, is it possible to fix threads to execute on certain cores. If that is possible, I also want to know if it is possible to execute one thread exclusively on a certain core, that is disallowing any other thread to execute on that core while that thread is executing.
That's what pthread_setaffinity_np(3) does.
The pthread_setaffinity_np() function sets the CPU affinity mask of
the thread thread to the CPU set pointed to by cpuset. If the call is
successful, and the thread is not currently running on one of the CPUs
in cpuset, then it is migrated to one of those CPUs.
As an example:
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(3, &set); /* Run only on the third CPU. */
pthread_setaffinity_np(thr, CPU_SETSIZE, &set);
You can also do it with sched_setaffinity(2) and gettid, but that manual page says:
If you are using the POSIX threads API, then use
pthread_setaffinity_np(3) instead of sched_setaffinity().