0

我正在运行 Linux,并且有这个代码片段,我想用它来操作 C 中的计时器,每 40 毫秒触发一个函数。到目前为止,我只尝试运行创建和启动新计时器的部分。但是我收到以下错误:

/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);
4

1 回答 1

2

我很确定这是因为您可能没有与实时库 (librt): 链接-lrt

有关其手册页的更多信息:

与 -lrt 链接。

于 2013-04-04T01:01:20.113 回答