私は Linux を実行しており、このコード スニペットを使用して、40 ミリ秒ごとに関数をトリガーする C のタイマーを操作したいと考えています。これまでのところ、新しいタイマーを作成して開始するセクションのみを実行しようとしています。ただし、次のエラーが発生します。
/tmp/ccA7MbyS.o: In function `main':
server.c:(.text+0x69e): undefined reference to `timer_create'
server.c:(.text+0x6be): undefined reference to `timer_settime'
collect2: ld returned 1 exit status
これらのメソッドをコメントアウトすると、コードは正常にコンパイルされます。何か案は?
#include <sys/time.h>
#include <signal.h>
#include <time.h>
// This struct is created to save information that will be needed by the timer,
// such as socket file descriptors, frame numbers and video captures.
struct send_frame_data {
int socket_fd;
// other fields
};
// This function will be called when the timer ticks
void send_frame(union sigval sv_data) {
struct send_frame_data *data = (struct send_frame_data *) sv_data.sival_ptr;
// You may retrieve information from the caller using data->field_name
// ...
}
// ...
// The following snippet is used to create and start a new timer that runs
// every 40 ms.
struct send_frame_data data; // Set fields as necessary
struct sigevent play_event;
timer_t play_timer;
struct itimerspec play_interval;
memset(&play_event, 0, sizeof(play_event));
play_event.sigev_notify = SIGEV_THREAD;
play_event.sigev_value.sival_ptr = &data;
play_event.sigev_notify_function = send_frame;
play_interval.it_interval.tv_sec = 0;
play_interval.it_interval.tv_nsec = 40 * 1000000; // 40 ms in ns
play_interval.it_value.tv_sec = 0;
play_interval.it_value.tv_nsec = 1; // can't be zero
timer_create(CLOCK_REALTIME, &play_event, &play_timer);
timer_settime(play_timer, 0, &play_interval, NULL);
// The following snippet is used to stop a currently running timer. The current
// task is not interrupted, only future tasks are stopped.
play_interval.it_interval.tv_sec = 0;
play_interval.it_interval.tv_nsec = 0;
play_interval.it_value.tv_sec = 0;
play_interval.it_value.tv_nsec = 0;
timer_settime(play_timer, 0, &play_interval, NULL);
// The following line is used to delete a timer.
timer_delete(play_timer);