fork download
  1. #include <iostream>
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <signal.h>
  6. #include <time.h>
  7. #include <errno.h>
  8. #include <assert.h>
  9.  
  10. #include <unistd.h>
  11. #include <sys/time.h>
  12.  
  13. static int alarm_pipe[2];
  14.  
  15. extern "C" {
  16. static int xsignal (int sig, void (*handler)(int))
  17. {
  18. struct sigaction sa;
  19. sa.sa_handler = handler;
  20. sigemptyset(&sa.sa_mask);
  21. sa.sa_flags = 0;
  22. return sigaction(sig, &sa, NULL);
  23. }
  24.  
  25. void sigalarm_handler (int)
  26. {
  27. if (write(alarm_pipe[1], "", 1) != 1) {
  28. char msg[] = "write: failed from sigalarm_handler\n";
  29. write(2, msg, sizeof(msg)-1);
  30. abort();
  31. }
  32. }
  33. }
  34.  
  35. int main ()
  36. {
  37. if (pipe(alarm_pipe) != 0) {
  38. perror("pipe");
  39. exit(EXIT_FAILURE);
  40. }
  41.  
  42. if (xsignal(SIGALRM, sigalarm_handler) != 0) {
  43. perror("sigaction");
  44. exit(EXIT_FAILURE);
  45. }
  46.  
  47. struct itimerval it = { { 0, 200000 }, { 0, 200000 } };
  48. if (setitimer(ITIMER_REAL, &it, 0) != 0) {
  49. perror("setitimer");
  50. exit(EXIT_FAILURE);
  51. }
  52.  
  53. char c;
  54. struct timeval tv;
  55. for (int i = 0; i < 10; ++i) {
  56. for (;;) {
  57. ssize_t alarm_pipe_read_result = read(alarm_pipe[0], &c, 1);
  58. if ((alarm_pipe_read_result < 0) && (errno == EINTR)) continue;
  59. assert(alarm_pipe_read_result == 1);
  60. break;
  61. }
  62. //... do sampling ...
  63. gettimeofday(&tv, 0);
  64. std::cerr << tv.tv_usec/1000 << std::endl;
  65. }
  66. }
  67.  
Success #stdin #stdout 0s 2848KB
stdin
Standard input is empty
stdout
Standard output is empty