On the use _linux of several Linux timing functions

Source: Internet
Author: User
Tags function prototype sleep terminates

In the process of program development, we have to use a number of timers, usually if the time precision is not high, you can use the Sleep,uslepp function to allow the process to sleep for a period of time to achieve timing,

The former unit is seconds (s), the latter is subtle (us), but sometimes we do not want the process to sleep blocking where, we need the process to execute normally, when the specified time to do the appropriate action,

Under Linux we generally use the alarm function and the Setitimer function to realize the timing function;

The following is a detailed analysis of the two functions:

(1) Alarm function

Alarm also known as the alarm clock function, it can set a timer in the process, when the timer specified time to, it sent to the process SIGALRM signal;

The alarm function prototype is as follows:

unsigned int alarm (unsigned int seconds);
Seconds is the specified number of seconds

Required header File
#include <unistd.h>

Function prototypes
unsigned int alarm (unsigned int seconds)

function arguments
Seconds: Specify the number of seconds

function return value
Success: If the process has set the alarm time before this alarm () is invoked, return the remaining time of the last alarm time, or return 0.
Error:-1

The following is a simple example of the alarm () function:

void Sigalrm_fn (int sig)  
 
{ 
  printf ("alarm!\n"); 
  Alarm (2); 
  return; 
} 
 
int main (void) 
 
{ 
  signal (SIGALRM, SIGALRM_FN);//The following function must be a alarm with an int parameter
  (1); 
  while (1)  
  pause (); 
 
}

(2) Setitimer () function

In Linux, if the timing requirements are not very accurate, the use of alarm () and signal () on the line, but if you want to achieve a high precision timing function, it is necessary to use the Setitimer function.

Setitimer () is the Linux API, not the C-language standard Library,setitimer () has two functions, one is to specify a period of time before the execution of a function, and the second is a period of time to perform a function of each cell;

Linux has arranged 3 internal timers for each task:

Itimer_real: A real-time timer that is always counted regardless of the mode in which the process is run (even when the process is suspended). Timed arrival, sending a SIGALRM signal to the process.

Itimer_virtual: This is not a real-time timer, when the process calculates the execution time of the process in user mode (that is, when the program executes). Sends a SIGVTALRM signal to the process after a scheduled arrival.

Itimer_prof: The process counts both in user mode (that is, when the program executes) and in core mode (that is, when the process is scheduled). Timed arrival generates SIGPROF signals. Itimer_prof Records take more time than itimer_virtual to schedule the process.

The timer is initialized, given an initial value, decreasing with time, decreasing to 0 and sending a signal while restoring the initial value. In the task, we can one or all three kinds of timers, but at the same time the same type of timer can only use one.

The Setitimer function prototype is as follows:

#include <sys/time.h>

    int setitimer (int which, const struct itimerval *new_value,
           struct itimerval *old_ value);

 Timer values are defined by the following structures:

      struct Itimerval {struct timeval
        ; * Next Value * *
        struct timeval it_value;  /* Current value *
      /};

      struct Timeval {
        time_t   tv_sec;     /* seconds * *
        suseconds_t tv_usec;    /* microseconds *
      /};

It_interval is used to specify how often the task is performed, and how long the it_value is used to save the current time from the task. For example, you specify it_interval to be 2 seconds (microsecond 0), at the beginning we set the It_value time to 2 seconds (microseconds 0), when one second, it_value reduce one to 1, then 1 seconds, then it_value reduced 1, into 0, This time the signal (tell the user time, can perform the task), and the system automatically resets the It_value time to the It_interval value, that is 2 seconds, and then count again

Here is a simple example of Setitimer:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/time.h>

void Test_func ()
{
  static count = 0;

  printf ("Count is%d\n", count++);
}

void Init_sigaction ()
{
  struct sigaction act;
     
  Act.sa_handler = Test_func; Set the function of processing signal
  act.sa_flags = 0;

  Sigemptyset (&act.sa_mask);
  Sigaction (Sigprof, &act, NULL);//time to send Sigrof signal
}

void Init_time ()
{struct
  itimerval val;
     
  Val.it_value.tv_sec = 1; 1 seconds to enable timer
  val.it_value.tv_usec = 0;

  Val.it_interval = Val.it_value; The timer interval is 1s

  setitimer (itimer_prof, &val, NULL);
}

int main (int argc, char **argv)
{

  init_sigaction ();
  Init_time ();

  while (1);

  return 0;
}

You can see a value that outputs one count per second:

The following are the results of the operation:

[Root@localhost 5th]#./test
The count is 0
The Count is 1
The Count is 2
The Count is 3
The Count is 4
The Count is 5
The Count is 6
The Count is 7
The Count is 8
The Count is 9

Appendix:

Signal

1. header file
#include <signal.h>

2. function
Set a corresponding action for a signal

3. Function prototype
void (*signal int signum,void (* handler) (int))) (int);

Decomposition to see:

typedef void (*sig_t) (int);
sig_t signal (int sig, sig_t func);

The first parameter is the target signal. The func parameter is a pointer to a function that handles the signal. This processing signal function comes with an int parameter and should return void.
The Func parameter can also be set to some of the following values:
Sig_ign: If the func parameter is set to Sig_ign, the signal will be ignored.
SIG_DFL: If the func parameter is set to SIG_DFL, the signal is processed according to the determined behavior.

4. Possible types of SIG signals

1) #define SIGHUP 1/* hangup * *

Sighup is a common signal used by UNIX system administrators. Many background service processes will re-read their configuration files after receiving the signal. However, the actual function of the signal is to notify the process that its control terminal is disconnected. The default behavior is to terminate the process.

2) #define SIGINT 2/* Interrupt * *

For UNIX users, SIGINT is another common signal. The ctrl-c combination of many shells makes this signal known to all. The official name of the signal is the interrupt signal. The default behavior is to terminate the process.

3) #define SIGQUIT 3/* Quit * *

The sigquit signal is used to receive the ctrl-/combination of the shell. In addition, it is used to tell the process to exit. This is a common signal that notifies the application to close by performing some exit actions before the end. The default behavior is to terminate the process and create a core dump.

4) #define Sigill 4/* illegal instr. (not reset when caught) * *

If an illegal instruction is included in the process being executed, the operating system sends a SIGILL signal to the process. If your program uses threads, or pointer functions, you might try to capture the signal to assist with debugging. ([color=red] Note: The original sentence is: "If your program makes use of the use of threads, or pointer functions, try to catch this signal If Possi BLE for aid in debugging. ". In the middle of the two use of, I do not know is the original book layout flaws or I really did not understand its significance; In addition, I often heard functions pointer, for pointer Functions,google, should be a FORTRAN inside things, Anyway, I really do not know, the exact meaning also please know brother treatise. [/color]) The default behavior is to terminate the process and create a core dump.

5) #define SIGTRAP 5/* Trace trap (not reset when caught) * *

Sigtrap This signal is defined by the POSIX standard for debugging purposes. When the signal is received by the debugging process, it means that it has reached a debug breakpoint. Once this signal is delivered, the process being debugged will stop and its parent process will be notified. The default behavior is to terminate the process and create a core dump.

6) #define SIGABRT 6/* ABORT () * *

SIGABRT provides a way to create a core dump at the same time that an exception terminates (abort) a process. However, if the signal is captured and the signal processing handle is not returned, the process does not terminate. The default behavior is to terminate the process and create a core dump.

7) #define SIGFPE 8/* Floating point Exception * *

When a floating-point error occurs in a process, the SIGFPE signal is sent to the process. For programs that handle complex mathematical operations, you are generally advised to capture the signal. The default behavior is to terminate the process and create a core dump.

8) #define SIGKILL 9/* Kill (cannot be caught or ignored) * *

Sigkill is one of the hardest to deal with in these signals. As you can see in the annotation next to it, this signal cannot be captured or ignored. Once the signal is delivered to a process, the process terminates. However, there are very few situations where Sigkill will not terminate the process. These rare situations occur when dealing with a "nondisruptive operation" (such as disk I/O). While such a situation rarely occurs, it can cause a process deadlock if it occurs. The only way to end a process is to reboot. The default behavior is to terminate the process.

9) #define SIGBUS/* Bus Error * *

As its name implies, the CPU generates a Sigbus signal when it detects errors on the data bus. This signal is generated when the program attempts to access a memory address that is not properly aligned. The default behavior is to terminate the process and create a core dump.

#define SIGSEGV/* Segmentation violation * *

SIGSEGV is a familiar signal to another C + + programmer. When the program does not have access to a protected memory address, or access to an invalid virtual memory address (dirty pointer, dirty pointers, is not synchronized with the contents of the backing store). For a wild pointer, see the http://en.wikipedia.org/wiki/Wild_pointer explanation. ), this signal is generated. The default behavior is to terminate the process and create a core dump.

One) #define SIGSYS/* Non-existent system call invoked * *

The Sigsys signal is delivered when the process executes a nonexistent system call. The operating system will deliver the signal and the process will be terminated. The default behavior is to terminate the process and create a core dump.

#define SIGPIPE/* Write on a pipe with no one to read it * *

A pipe acts as a telephone, allowing communication between processes. If a process tries to write to a pipe, but the other side of the pipe does not have a respondent, the operating system delivers the sigpipe signal to the annoying process (the process that is intended to be written). The default behavior is to terminate the process.

#define SIGALRM/* Alarm clock/* *

When the timer of the process expires, the SIGALRM signal is delivered (delivered) to the process. These timers will be mentioned later in this chapter
The Setitimer and alarm invocation settings. The default behavior is to terminate the process.

#define SIGTERM/* software termination signal from KILL * *

The sigterm signal is sent to the process, notifying the process that it is time to terminate and do some cleanup activity before terminating. The sigterm signal is the default signal sent by the KILL command for UNIX, as well as the default signal sent to the process when the operating system shuts down. The default behavior is to terminate the process.

#define Sigurg/* Urgent condition on IO channel * *

When something happens on a socket that is open on a process, Sigurg is sent to the process. If the process does not capture this signal, it will be discarded. The default behavior is to discard this signal.

#define SIGSTOP/* sendable stop signal not from TTY */

This signal cannot be captured or ignored. Once the process receives the sigstop signal, it stops immediately (stop) until another sigcont is received
Signal so far. The default behavior is to stop the process until a sigcont signal is received.

#define SIGTSTP/* stop signal from TTY */

SIGSTP are similar to Sigstop, and the difference is that SIGSTP signals can be captured or ignored. The Shell delivers (deliver) this signal to the process when it receives the ctrl-z from the keyboard. The default behavior is to stop the process until a sigcont signal is received.

#define SIGCONT/* Continue a stopped process * *

Sigcont is also an interesting signal. As mentioned earlier, this signal is used to tell the process to resume running when the process stops. The interesting thing about this signal is that it can't be ignored or blocked, but it can be captured. This makes sense: because the process is probably unwilling to ignore or block the sigcont signal, what if the process receives Sigstop or SIGSTP? The default behavior is to discard the signal.

#define SIGCHLD/* To parent in child stop or exit * *

SIGCHLD is introduced by Berkeley UNIX and has a better interface than implementations on SRV 4 UNIX. If the signal is a process without traceability (not a retroactive processes), then the BSD Sigchid signal implementation will be better. In the implementation of System V UNIX, if the process requires that the signal be captured, the operating system checks for the existence of any incomplete child processes that are child processes that have exited exit, and who are waiting for the parent process to call wait to collect their status. If a child process exits with some termination information (terminating information), the signal processing handle is invoked. Therefore, just asking to capture this signal will cause the signal processing handle to be invoked (that is, the "traceability of the signals" above), which is a rather confusing situation. Once a process's subprocess state has changed, the SIGCHLD signal is sent to the process. As I mentioned in the previous chapter, although the parent process can fork out the child process, there is no need to wait for the child process to exit. In general this is not very good, because in this case, once the process exits, it may become a zombie process. However, if the parent process captures the SIGCHLD signal, it can use one of the wait series calls to collect the status of the subprocess, or to determine what is going on. When a SIGSTOP,SIGSTP or sigconf signal is sent to a child process, the SIGCHLD signal is also sent to the parent process. The default behavior is to discard the signal.

#define Sigttin/* to readers pgrp upon background tty read * *

When a background process attempts to perform a read operation, the Sigttin signal is sent to the process. The process will block until the sigcont signal is received. The default behavior is to stop the process until the sigcont signal is received.

#define Sigttou/* like Ttin if (tp->t_local&ltostop) */

The Sigttou signal is very similar to the sigttin, except that the Sigttou signal occurs because the background process tries to perform a write operation on a TTY that has the Tostop attribute set. However, if TTY does not set this property, Sigttou will not be sent. The default behavior is to stop the process until the sigcont signal is received.

#define SIGIO/* input/output possible signal * *

If the process has I/O operations on a file descriptor, the Sigio signal is sent to the process. Processes can be set by Fcntl. The default behavior is to discard the signal.

#define SIGXCPU/* exceeded CPU time limit * *

If the process exceeds the CPU limit (CPU limit) It can use, the SIGXCPU signal is sent to it. This restriction can use the Setrlimit settings that are discussed later. The default behavior is to terminate the process.

#define SIGXFSZ/* exceeded file size Limit/*

If the process exceeds the file size limit it can use, the SIGXFSZ signal is sent to it. We will continue to discuss this signal later. The default behavior is to terminate the process.

#define SIGVTALRM/* Virtual Time alarm * *

If the process exceeds the virtual timer count it sets, the SIGVTALRM signal is sent to it. The default behavior is to terminate the process.

#define SIGPROF/* Profiling time alarm * *

When a timer is set, SIGPROF is another signal that will be sent to the process. The default behavior is to terminate the process.

#define SIGWINCH/* Window size changes * *

When the process adjusts the line or column of the terminal (such as increasing the size of your xterm), the sigwinch signal is sent to the process. The default behavior is to discard the signal.

#define SIGUSR1/* User Defined signal 1 * *

#define SIGUSR2/* User Defined Signal 2 * *

SIGUSR1 and SIGUSR2 These two signals are designed to be specified by the user. They can be set up to do whatever you need. In other words, the operating system does not have any behavior associated with the two signals. The default behavior is to terminate the process. It seems that these two sentences are a bit contradictory when translated according to the original meaning. )

5. Examples

5.1. Linux under the CTRL + C under Windows implementation of a

The usual practice under Linux:

Signal (SIGINT, sigfunc); Set signal
void Sigfunc (int signo)
  {
   ...//handling signal-related operations
  }

The following is the implementation of CTRL + C under Linux under Windows

#include <stdio.h>
  #include <windows.h>
  static is_loop = 1;
  function to capture the console CTRL + C event
  BOOL Ctrlhandler (DWORD fdwctrltype)
  {
   switch (fdwctrltype)
   {/
   * Handle the CT Rl-c signal. * * Case
   ctrl_c_event:
     printf ("ctrl_c_event \ n");
     break;
   Case ctrl_close_event:
     printf ("ctrl_close_event \ n");
     break;
   Case ctrl_break_event:
     printf ("ctrl_break_event \ n");
     break;
   Case ctrl_logoff_event:
     printf ("ctrl_logoff_event \ n");
     break;
   Case ctrl_shutdown_event:
     printf ("ctrl_shutdown_event \ n");
     break;
   Default: Return
     FALSE;
   }
   Is_loop = 0;
   return (TRUE);
  }

  int main (int argc, char *argv[])
  {
   printf ("Set Console Ctrl handler\n");
   SetConsoleCtrlHandler ((phandler_routine) Ctrlhandler, TRUE);
   while (Is_loop);
   return 0;
  }

5.2.Linux implementation of CTRL + C under Windows two

#include <stdio.h>
  #include <windows.h>
  #define CONTRL_C_HANDLE () signal (3, exit)
  int main ( int argc, char *argv[])
  {
   printf ("Set Console Ctrl handler\n");
   Contrl_c_handle ();
   while (1);
   System ("PAUSE");
   return 0;
  }

The above is a small series for everyone to talk about the use of several Linux timing functions of all the content, I hope that many support cloud Habitat Community ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.