Common Linux C functions-Signal Processing

Source: Internet
Author: User
Common Linux C functions-Signal Processing-general Linux technology-Linux programming and kernel information. For more information, see the following section. Alarm)
Related functions: signal, sleep

Header file # include

Define the function unsigned int alarm (unsigned int seconds );

Function Description alarm () is used to set the signal SIGALRM to be sent to the current process after the specified number of seconds after the seconds parameter. If the seconds parameter is 0, the previously set alarm is canceled and the remaining time is returned.

Return the remaining seconds of the previous alarm. If no alarm is set, return 0.

Example # include
# Include
Void handler (){
Printf ("hello \ n ");
}
Main ()
{
Int I;
Signal (SIGALRM, handler );
Alarm (5 );
For (I = 1; I <7; I ++ ){
Printf ("sleep % d... \ n", I );
Sleep (1 );
}
}

Run sleep 1...
Sleep 2...
Sleep 3...
Sleep 4...
Sleep 5...
Hello
Sleep 6...

 




Kill (send a signal to a specified process)
Related functions: raise, signal

Header file # include
# Include

Define the int kill (pid_t pid, int sig) function );

Function Description: kill () can be used to send signals specified by the sig parameter to the process specified by the pid parameter. The pid parameter can be used in the following situations:
Pid> 0: send the signal to the process with the pid ID.
Pid = 0 send the signal to all processes in the same process group as the current process
Pid =-1 broadcasts signals to all processes in the system
Pid <0 transmits the signal to all processes whose process ID is the absolute value of pid
For the signal numbers represented by the sig parameter, see Appendix D.

If the return value is successfully executed, 0 is returned. If an error exists,-1 is returned.

The error code EINVAL parameter sig is invalid.
The process or process group specified by the ESRCH Parameter pid does not exist.
The EPERM permission is insufficient to send signals to the specified process.

Example # include
# Include
# Include
# Include
Main ()
{
Pid_t pid;
Int status;
If (! (Pid = fork ())){
Printf ("Hi I am child process! \ N ");
Sleep (10 );
Return;
}
Else {
Printf ("send signal to child process (% d) \ n", pid );
Sleep (1 );
Kill (pid, SIGABRT );
Wait (& status );
If (WIFSIGNALED (status ))
Printf ("chile process receive signal % d \ n", WTERMSIG (status ));
}
}

Execute sen signal to child process (3170)
Hi I am child process!
Child process receive signal 6

 




Pause (pause the process until the signal appears)
Related functions: kill, signal, sleep

Header file # include

Define the int pause (void) function );

Function Description: pause () will suspend the current process (into sleep state) until it is interrupted by the signal.

The returned value is-1.

The error code EINTR indicates that the function is interrupted when a signal arrives.

 




Sigaction (query or set the signal processing method)
Related functions: signal, sigprocmask, sigpending, sigsuspend

Header file # include

Define the int sigaction (int signum, const struct sigaction * act, struct sigaction * oldact) function );

Function Description: sigaction () sets the signal processing function based on the signal number specified by signum. The signum parameter can specify all signals other than SIGKILL and SIGSTOP.
For example, the parameter structure sigaction is defined as follows:
Struct sigaction
{
Void (* sa_handler) (int );
Sigset_t sa_mask;
Int sa_flags;
Void (* sa_restorer) (void );
}
Sa_handler this parameter is the same as the signal () parameter handler, representing a new signal processing function. For other meanings, see signal ().
Sa_mask is used to set the signal specified by sa_mask to be temporarily shelved when processing this signal.
Sa_restorer is not used.
Sa_flags is used to set other operations related to signal processing. The following values are available.
OR operation (|) Combination
A_NOCLDSTOP: If the signum parameter is SIGCHLD, the parent process is not notified when the child process is paused.
SA_ONESHOT/SA_RESETHAND: Before calling a new signal processing function, change the Signal Processing Method to the system preset method.
SA_RESTART: system calls that are interrupted by signals will be restarted on their own.
SA_NOMASK/SA_NODEFER: Ignore the re-arrival of the signal before processing the signal.
If the oldact parameter is not a NULL pointer, the original signal processing method will be returned from the sigaction structure.

If the return value is successfully executed, 0 is returned. If an error exists,-1 is returned.

The error code EINVAL parameter signum is invalid, or an attempt to intercept the SIGKILL/SIGSTOPSIGKILL Signal
The EFAULT parameter act and the oldact pointer address cannot be accessed.
EINTR this call is interrupted

Example # include
# Include
Void show_handler (struct sigaction * act)
{
Switch (act-> sa_flags)
{
Case SIG_DFL: printf ("Default action \ n"); break;
Case SIG_IGN: printf ("Ignore the signal \ n"); break;
Default: printf ("0x % x \ n", act-> sa_handler );
}
}
Main ()
{
Int I;
Struct sigaction act, oldact;
Act. sa_handler = show_handler;
Act. sa_flags = SA_ONESHOT | SA_NOMASK;
Sigaction (SIGUSR1, & act, & oldact );
For (I = 5; I <15; I ++)
{
Printf ("sa_handler of signal % 2d =". I );
Sigaction (I, NULL, & oldact );
}
}

Execute sa_handler of signal 5 = Default action
Sa_handler of signal 6 = Default action
Sa_handler of signal 7 = Default action
Sa_handler of signal 8 = Default action
Sa_handler of signal 9 = Default action
Sa_handler of signal 10 = 0x8048400
Sa_handler of signal 11 = Default action
Sa_handler of signal 12 = Default action
Sa_handler of signal 13 = Default action
Sa_handler of signal 14 = Default action

 




Sigaddset (add a signal to the signal set)
Related functions: sigemptyset, sigfillset, sigdelset, sigismember

Header file # include

Defines the int sigaddset (sigset_t * set, int signum) function );

Function Description: sigaddset () is used to add signals represented by the signum parameter to the set Signal set parameter.

If the return value is successfully executed, 0 is returned. If an error exists,-1 is returned.

Error Code EFAULT parameter set pointer address cannot be accessed
The sigval parameter signum is invalid.

 




Sigdelset (delete a signal from the signal set)
Related functions: sigemptyset, sigfillset, sigaddset, sigismember

Header file # include

Defines the int sigdelset (sigset_t * set, int signum) function );

Function Description: sigdelset () is used to delete signals represented by the signum parameter from the set signal set.

If the return value is successfully executed, 0 is returned. If an error exists,-1 is returned.

Error Code EFAULT parameter set pointer address cannot be accessed
The sigval parameter signum is invalid.

 




Sigemptyset (initialize Signal Set)
Related functions: sigaddset, sigfillset, sigdelset, and sigismember

Header file # include

Define the int sigemptyset (sigset_t * set) function );

Function Description: sigemptyset () is used to initialize and clear the set Signal set parameter.

If the return value is successfully executed, 0 is returned. If an error exists,-1 is returned.

Error Code EFAULT parameter set pointer address cannot be accessed

 




Sigfillset (add all signals to the signal set)
Related functions: sigempty, sigaddset, sigdelset, sigismember

Header file # include

Define the int sigfillset (sigset_t * set) function );

Function Description: sigfillset () is used to initialize the set Signal set parameter, and then add all signals to this signal set.

If the return value is successfully executed, 0 is returned. If an error exists,-1 is returned.

Note: The set pointer address of the EFAULT parameter cannot be accessed.

 




Sigismember (test whether a signal has been added to the signal set)
Related functions: sigemptyset, sigfillset, sigaddset, and sigdelset

Header file # include

Defines the int sigismember (const sigset_t * set, int signum) function );

Function Description: sigismember () is used to test whether the signal represented by the signum parameter has been added to the set Signal set parameter. If the signal already exists in the signal set, 1 is returned; otherwise, 0 is returned.

If this signal already exists in the returned Signal Set, 1 is returned. If not, 0 is returned. If an error exists,-1 is returned.

Error Code EFAULT parameter set pointer address cannot be accessed
The sigval parameter signum is invalid.

 




Signal (set signal Processing Method)
Related functions: sigaction, kill, raise

Header file # include

Define the function void (* signal (int signum, void (* handler) (int );

Function Description: signal () sets the signal processing function based on the signal number specified by signum. When the specified signal arrives, the function execution specified by handler is redirected. If the handler parameter is not a function pointer, it must be one of the following two constants:
SIG_IGN ignores the signal specified by the signum parameter.
SIG_DFL resets the signal specified by signum as the core preset signal processing method.
For signal numbers and descriptions, see Appendix D.

Returns the pointer to the previous signal processing function. If an error occurs, returns SIG_ERR (-1 ).

Note: after the signal jumps to the Custom handler processing function, the system automatically switches the processing function back to the preset processing method. If you want to change this operation, use sigaction ().

For an example, see alarm () or raise ().

 




Sigpending (query signals shelved)
Related functions: signal, sigaction, sigprocmask, sigsuspend

Header file # include

Define the int sigpending (sigset_t * set) function );

Function Description: sigpending () returns the shelved signal set by the set pointer.

If the return value is successful, 0 is returned. If an error exists,-1 is returned.

Error Code EFAULT parameter set pointer address cannot be accessed
EINTR this call is interrupted.

 




Sigprocmask (query or set the signal mask)
Related functions: signal, sigaction, sigpending, sigsuspend

Header file # include

Define the int sigprocmask (int how, const sigset_t * set, sigset_t * oldset) function );

Function Description: sigprocmask () can be used to change the current signal mask. The operation is determined by the parameter "how ".
The new SIG_BLOCK signal mask is set by the current signal mask and the signal mask specified by the set parameter.
SIG_UNBLOCK deletes the current signal mask from the signal mask specified by the set parameter.
SIG_SETMASK sets the current signal mask to the signal mask specified by the set parameter.
If the oldset parameter is not a NULL pointer, the current signal mask will return this pointer.

If the return value is successfully executed, 0 is returned. If an error exists,-1 is returned.

The set parameter of the error code EFAULT cannot be accessed by the oldset pointer address.
EINTR this call is interrupted

 




Sleep (pause the process for a period of time)
Related functions: signal, alarm

Header file # include

Defines the function unsigned int sleep (unsigned int seconds );

Function Description: sleep () will suspend the current process until the time specified by seconds is reached or the signal is interrupted.

Return Value: if the process is paused to the time specified by seconds, 0 is returned. If a signal is interrupted, the remaining seconds are returned.

 




Ferror (check whether an error occurs in the file Stream)
Related functions clearerr, perror

Header file # include

Defines the int ferror (FILE * stream) function );

Function Description: ferror () is used to check whether the file stream specified by the stream parameter has an error. If an error occurs, a non-zero value is returned.

Return Value: if an error occurs in the file stream, a non-0 value is returned.

 




Perror (print the error cause string)
Related Function strerror

Header file # include

Define the void perror (const char * s) function );

Function Description perror () is used to output the cause of the previous function error to the standard error (stderr ). The string referred to by parameter s is printed first, followed by the error cause string. The cause of this error is determined based on the value of the global variable errno.

Return Value

Example # include
Main ()
{
FILE * fp;
Fp = fopen ("/tmp/noexist", "r + ");
If (fp = NULL) perror ("fopen ");
}

Run $./perror
Fopen: No such file or diretory

 




Strerror (return the description string of the error cause)
Related Function perror

Header file # include

Define the function char * strerror (int errnum );

Function Description strerror () is used to query the description string of the error cause based on the error code of the errnum parameter, and then return the string pointer.

Return the string pointer that describes the cause of the error.

Example/* display the error cause descriptions of error codes 0 to 9 */
# Include
Main ()
{
Int I;
For (I = 0; I <10; I ++)
Printf ("% d: % s \ n", I, strerror (I ));
}

Execute 0: Success
1: Operation not permitted
2: No such file or directory
3: No such process
4: Interrupted system call
5: Input/output error
6: Device not configured
7: Argument list too long
8: Exec format error
9: Bad file descriptor

 




Mkfifo (create a named pipe)
Related functions: pipe, popen, open, umask

Header file # include
# Include

Defines the int mkfifo function (const char * pathname, mode_t mode );

Function Description: mkfifo () creates a special FIFO file according to the pathname parameter. This file must not exist, and the parameter mode is the permission of this file (mode % ~ Umask), so the umask value also affects the permissions of the FIFO file. Other processes created by Mkfifo () can read and write common files. When open () is used to open a FIFO file, the O_NONBLOCK flag will be affected.
1. When the O_NONBLOCK flag is used, the operation to open the FIFO file to read will be immediately returned, but if no other process opens the FIFO file for reading, the write operation will return the ENXIO error code.
2. If the O_NONBLOCK flag is not used, the operation to enable FIFO to read will not be returned until other processes open the FIFO file for writing. Similarly, operations to open a FIFO file and write data will not be returned until other processes open a FIFO file to read data.

If the returned value is successful, 0 is returned; otherwise,-1 is returned. The error cause is stored in errno.

The directory path specified by the EACCESS parameter pathname in the error code cannot be executed.
The file specified by the EEXIST parameter pathname already exists.
The path name of the pathname parameter is too long.
The directory in the pathname parameter of ENOENT does not exist.
The ENOSPC file system has insufficient space.
The directory in the pathname path of the ENOTDIR parameter exists but is not a real directory.
The file specified by the EROFS parameter pathname exists in the read-only file system.

Example # include
# Include
# Include
Main ()
{
Char buffer [80];
Int fd;
Unlink (FIFO );
Mkfifo (FIFO, 0666 );
If (fork ()> 0 ){
Char s [] = "hello! \ N ";
Fd = open (FIFO, O_WRONLY );
Write (fd, s, sizeof (s ));
Close (fd );
}
Else {
Fd = open (FIFO, O_RDONLY );
Read (fd, buffer, 80 );
Printf ("% s", buffer );
Close (fd );
}
}

Execute hello!

 




Pclose (disable pipeline I/O)
Related Function popen

Header file # include

Defines the int pclose (FILE * stream) function );

Function Description: pclose () is used to close the pipeline and file pointer created by popen. The parameter stream is the object pointer returned by the previous popen.

Returns the end status of the sub-process. If an error exists,-1 is returned. The error cause is stored in errno.

The error code ECHILD pclose () cannot get the end status of the sub-process.

For more information, see popen ().

 




Pipe (pipeline creation)
Related functions: mkfifo, popen, read, write, fork

Header file # include

Define the int pipe function (int filedes [2]);

Function Description pipe () creates an MPS queue and returns the file description from the filedes array. Filedes [0] is the read end in the pipeline, and filedes [1] is the write end of the pipeline.

If the returned value is successful, zero is returned. Otherwise,-1 is returned. The error cause is stored in errno.

The error code EMFILE process has used up the maximum number of file descriptions.
The ENFILE system does not have a file description word available.
The filedes array address of the EFAULT parameter is invalid.

Example/* the parent process uses a pipeline to send the string "hello! \ N "is passed to the sub-process and displayed */
# Include
Main ()
{
Int filedes [2];
Char buffer [80];
Pipe (filedes );
If (fork ()> 0 ){
/* Parent process */
Char s [] = "hello! \ N ";
Write (filedes [1], s, sizeof (s ));
}
Else {
/* Sub-process */
Read (filedes [0], buffer, 80 );
Printf ("% s", buffer );
}
}

Execute hello!

 




Popen (create pipeline I/O)
Related functions: pipe, mkfifo, pclose, fork, system, and fopen

Header file # include

Define the function FILE * popen (const char * command, const char * type );

Function Description: popen () calls fork () to generate sub-processes, and then calls/bin/sh-c from the sub-process to execute the command of the parameter command. You can use "r" to indicate reading, and "w" to indicate writing. According to this type value, popen () establishes a pipeline to connect to the standard output device or standard input device of the child process, and then returns a file pointer. Then the process can use this file pointer to read the output device of the sub-process or write it to the standard input device of the sub-process. In addition, all functions that use FILE * operations can also be used, except fclose.

If the returned value is successful, the file pointer is returned. Otherwise, NULL is returned. The error cause is stored in errno.

The error code EINVAL parameter type is invalid.

Note: Avoid using popen () when writing programs with SUID/SGID permissions. popen () inherits environment variables, which may cause system security problems.

Example # include
Main ()
{
FILE * fp;
Char buffer [80];
Fp = popen ("cat/etc/passwd", "r ");
Fgets (buffer, sizeof (buffer), fp );
Printf ("% s", buffer );
Pclose (fp );
}

Run root: x: 0 0: root:/bin/bash.
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.