Linux setitimer parameter settings

Source: Internet
Author: User

Reprinted from: http://www.cublog.cn/u2/76349/showart_2227666.html

 

Linux setitimer for computer players commonly used software, then I will learn and study Linux
Setitimer, here to discuss with you how to use Linux setitimer, hope to be useful to everyone. Linux
Setitimer () is a Linux API, not the standard library of C language, Linux
Setitimer () has two functions: one is to execute a function after a specified period of time, and the other is to execute a function after each period of time. The following program demo
How to use Linux setitimer ().

 
 
  1. view plaincopy to clipboardprint?/*    
  2. Filename    : timer.cpp    
  3. Compiler    : gcc 4.1.0 on Fedora Core 5    
  4. Description : Linux setitimer() set the interval to run function    
  5. Synopsis    : #include <sys/time.h>    
  6. int Linux setitimer(int which, const struct itimerval *value, struct itimerval *ovalue);    
  7. struct itimerval {    
  8. struct timerval it_interval;    
  9. struct timerval it_value;    
  10. };    
  11. struct timeval {    
  12. long tv_sec;    
  13. long tv_usec;    
  14. }  
  15. Release     : 11/25/2006    
  16. */     
  17. #include <stdio.h>    // for printf()     
  18. #include <unistd.h>   // for pause()     
  19. #include <signal.h>   // for signal()     
  20. #include <string.h>   // for memset()     
  21. #include <sys/time.h> // struct itimeral. Linux setitimer()     
  22. void printMsg(int);     
  23. int main() {     
  24. // Get system call result to determine successful or failed     
  25. int res = 0;     
  26. // Register printMsg to SIGALRM     
  27. signal(SIGALRM, printMsg);     
  28. struct itimerval tick;     
  29. // Initialize struct     
  30. memset(&tick, 0, sizeof(tick));     
  31. // Timeout to run function first time     
  32. tick.it_value.tv_sec = 1;  // sec     
  33. tick.it_value.tv_usec = 0; // micro sec.     
  34. // Interval time to run function     
  35. tick.it_interval.tv_sec = 1;     
  36. tick.it_interval.tv_usec = 0;     
  37. // Set timer, ITIMER_REAL : real-time to decrease timer,     
  38. //            send SIGALRM when timeout     
  39. res = Linux setitimer(ITIMER_REAL, &tick, NULL);     
  40. if (res) {     
  41. printf("Set timer failed!!/n");     
  42. }     
  43. // Always sleep to catch SIGALRM signal     
  44. while(1) {     
  45. pause();     
  46. }     
  47. return 0;       
  48. }     
  49. void printMsg(int num) {     
  50. printf("%s","Hello World!!/n");     
  51. }     
  52.  

When the timer time executed by Linux setitimer () is reached, it will call sigalrm
Signal, so the function to be executed by signal () is specified to sigalrm in line 30th. Call Linux on line 3
Setitimer () sets timer, but Linux setitimer ()

The second parameter is sturct, which is used to set the timeout time, so the 36th rows
Set this struct in 40 rows. Itimerval. it_value sets the number of seconds after the first function execution,
Itimerval. it_interval is set to execute the function every several seconds. If you only want to delay the execution of the function for a period of time, you only need to set
Itimerval. it_value.

If you want to set an interval to execute the function for a period of time, you must set both it_value and it_interval. Otherwise
The first time the funtion cannot be executed, let alone the subsequent interval. The TV _sec values of rows 36th and 39th are sec, 37th and 40 Act micro.
SEC (0.001 sec ).
Itimer_real, the first parameter of row 43rd, indicates that timer is reduced in real-time mode, and sigalrm signal is sent out in timeout.

The third parameter stores the old timeout value. If this parameter is not required, specify NULL. 47th
Line pause (), the command system enters the sleep state, wait for any signal, must use while (1) infinite loop execution pause (), so as to continue to receive
Sigalrm signal executes the function at intervals. If while (1) is removed, the function will only be executed once.

 

3. Sample program

Example 1: Send and process signals to see how the sigaction function is used.
Code

# Include <signal. h>
# Include <sys/types. h>
# Include <unistd. h>
Void user_func (INT, siginfo_t *, void *);

Int main (INT argc, char ** argv)
{
Struct sigaction Act;
Int SIG;
Sig = atoi (argv [1]);

Sigemptyset (& act. sa_mask );
Act. sa_flags = sa_siginfo;
Act. sa_sigaction = (void *) user_func;

If (sigaction (SIG, & act, null) <0)
{
Printf ("Install Sigal error/N ");
}

While (1)
{
Sleep (2 );
Printf ("Wait for the signal/N ");
}
}
Void user_func (int signum, siginfo_t * info, void * myact)
{
Printf ("receive signal % d/n", SIGNUM );
Sleep (5 );
}

Execute CC-o act. C on a terminal
$./Act 8 &
[1] 992
$ Wait for the signal
$

Execute on another terminal

# Kill-S 8 992

Look ..

$ Receive signal 8

Example 2: signal blocking and Signal Set Operations

Code

# Include <signal. h>
# Include <unistd. h>
Void user_func (INT );
Main ()
{
Sigset_t new_mask, old_mask, pending_mask;
Struct sigaction Act;

Sigemptyset (& act. sa_mask );
Act. sa_flags = sa_siginfo;
Act. sa_sigaction = (void *) user_func;

If (sigaction (sigrtmin + 10, & act, null ))
Printf ("Install signal sigrtmin + 10 error/N ");

Sigemptyset (& new_mask );
Sigaddset (& new_mask, sigrtmin + 10 );

If (sigprocmask (sig_block, & new_mask, & old_mask ))
Printf ("Block Signal sigrtmin + 10 error/N ");

Sleep (20 );

Printf ("/n/Nnow begin to get pending mask and unblock sigrtmin + 10/n ");
If (sigpending (& pending_mask) <0)
Printf ("Get pending mask error/N ");
If (sigismember (& pending_mask, sigrtmin + 10 ))
Printf ("signal sigrtmin + 10 is pending/N ");

If (sigprocmask (sig_setmask, & old_mask, null) <0)
Printf ("unblock signal error/N ");

Printf ("signal unblocked, OK.../n ");
}
Void user_func (int signum)
{
Printf ("receive signal % d/N", SIGNUM );
}

$ CC-o sus. c
$./SUS &
[1] 997

Another Console
# Kill-s 42 PID

Look...

$
Now begin to get pending mask and unblock sigrtmin + 10

Signal sigrtmin + 10 is pending
Receive signal 42
Signal unblocked, OK ......

[1] + exit 31./d
$

Example 3: Signal

Code

# Include <signal. h>
# Include <unistd. h>
# Include <stdio. h>
# Define damo
Void user_func (INT No)
{
Switch (NO)
{
Case 1:
Printf ("Get sighup./N ");
Break;
Case 2:
Printf ("Get SIGINT/N ");
Break;
Case 3:
Printf ("Get sigquit/N ");
Break;
Default:
Printf ("What Wan Yi A/n ");
Break;
}

}
Int main ()
{
Printf ("rocess ID is % d/N", getpid ());

# Ifdef damo
Signal (sighup, user_func );
Signal (SIGINT, user_func );
Signal (sigquit, user_func );
Signal (sigbus, user_func );
# Else
Signal (sighup, sig_ign );
Signal (SIGINT, sig_ign );
Signal (sigquit, sig_ign );
Signal (sigbus, sig_dfl );
# Endif

While (1)
;
}

This is a centralized display of signal usage, which is also a frequently used method. To be honest, SCO is too old .. You can only use this function.
During the test, you can view the # define Damo annotation and no annotation. Profound Understanding of signal usage.

BTW: Signal (SIGINT, sig_ign );
Signal (sigquit, sig_ign );

After ignoring these signals, a process terminal can be unrelated, even if you exit this TTY. Of course, the kill signal cannot be blocked.
This method is mostly used in the daemon process.

$ CC-o si. c
$./Si

Process ID is 1501

On another tty
# Ps-ef
Bank 1501 1465 51 00:00:13 pts/0./Si
Bank 1502 800 0 00:00:00 pts/1 PS-ef
#
Note that this time is 1456.
You turn off the TTY./Si.
Then you
# Ps-ef
Bank 1501 1 50? 00:00:59./Si
Bank 1503 800 0 00:00:00 pts/1 PS-ef
Pay attention to the 1 and ?, Do you know what this process is? Cheng jingla. Haha ~~

Example 4: pause function
Code

# Include <unistd. h>
# Include <stdio. h>
# Include <signal. h>
Void user_func ()
{
Printf ("/n/ncatch a signal SIGINT/N ");
}

Int main ()
{
Printf ("pid = % d/n", getpid ());
Signal (SIGINT, user_func );
Pause ();
Printf ("receive a signal/n ");
}

In this example, the program starts to run, just as it enters an endless loop, because the process is waiting for a signal,
When we press Ctrl-C, the signal is captured and the pause is out of the waiting state.

Example 5: The following is a simple example of setitimer calling.

Code

# Include <signal. h>
# Include <unistd. h>
# Include <stdio. h>
# Include <sys/time. h>

Void user_func (INT sig)
{
If (Sig = sigalrm)
Printf ("catch a signal sigalrm/N ");
Else if (Sig = sigvtalrm)
Printf ("catch a signal sigvtalrm/N ");
}

Int main ()
{
Struct itimerval value, ovalue, value2;

Printf ("rocess ID is = % d/N", getpid ());

Signal (sigalrm, user_func );
Signal (sigvtalrm, user_func );

Value. it_value. TV _sec = 1;
Value. it_value. TV _usec = 0;
Value. it_interval. TV _sec = 1;
Value. it_interval. TV _usec = 0;

Setitimer (itimer_real, & Value, & ovalue );

Value2.it _ value. TV _sec = 1;
Value2.it _ value. TV _usec = 500000;
Value2.it _ interval. TV _sec = 1;
Value2.it _ interval. TV _usec = 500000;

Setitimer (itimer_virtual, & value2, & ovalue );

While (1 );
}

In this example, a sigalrm is sent every 1 second, and a sigvtalrm signal is sent every 1.5 seconds:

The result is as follows:
$./Ti
Progress ID is = 1734
Catch a signal sigalrm
Catch a signal sigvtalrm
Catch a signal sigalrm
Catch a signal sigalrm
Catch a signal sigvtalrm
Catch a signal sigalrm
Catch a signal sigvtalrm
Catch a signal sigalrm
Catch a signal sigalrm
Catch a signal sigvtalrm
Catch a signal sigalrm
Catch a signal sigvtalrm
Catch a signal sigalrm
Catch a signal sigalrm
Catch a signal sigvtalrm

CTRL + C interrupted.
....

I began to like the setitimer function...

Iv. Supplement

I have to introduce the functions of setjmp and longjmp.

When using signals, we can see that the process is required to directly return from the original system call after checking that the signal is received, rather than waiting until the call is completed.
This process suddenly changes its context, that is, the result of using setjmp and longjmp. Setjmp saves the saved context to the user zone and continues in the old
In the context. This means that a process executes a system call. When it goes to sleep for resources or other reasons, the Kernel performs setjmp for the process. If
The kernel calls longjmp for the process when the process cannot go to sleep. This operation is performed by the kernel to save the original setjmp call to the process.
The context of the user zone is restored to the current context, so that the process can restore the status before waiting for resources, and the kernel is setjmp and returns 1, so that the process knows
This system call failed. This is what they do.

Please try waitpid again if you have time .. Are very useful.

5. Postscript

Signal processing from the previous use to the formation of the final document, each time it feels very difficult, in fact, it is quite biased. After all, signal us
Generally, there is less contact and less use. In fact, we don't want to talk about signal color changes. After careful research, we found it interesting.
I have not directly used signals to process a large number of things. They are simple to use signals. There are few examples and many examples.
All examples are based on network materials. Many materials are based on the information of netizens, especially those of Zheng yanxing.

Related Article

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.