C language to manipulate the process of the signal of the correlation function using details

  • 2020-04-02 03:21:33
  • OfStack

C signal() function: sets how the signal is processed
The header file:


#include <signal.h>

Definition function:


void (*signal(int signum, void(* handler)(int)))(int);

Signal () will set the signal handler according to the signal number specified by the parameter signum. When the specified signal arrives, it will jump to the function specified by the parameter handler. If the parameter handler is not a function pointer, it must be one of the following two constants:
1. SIG_IGN ignores the signal specified by the parameter signum.
2. SIG_DFL resets the signal specified by the parameter signum to the signal processing mode preset by the core.

Please refer to appendix D for the number and description of the signal

Return value: returns the previous signal handler pointer and SIG_ERR(-1) if there is an error.

Note: after the signal jumps to the execution of the custom handler function, the system will automatically change this handler function back to the original default processing mode of the system. If you want to change this operation, use sigaction() instead.

C kill() function: sends a signal to the specified process
The header file:


#include <sys/types.h>  #include <signal.h>

Function: int kill(pid_t pid, int sig);

Kill () can be used to send the signal specified by parameter sig to the process specified by parameter pid. There are several cases of parameter pid:
1, the pid > 0 sends a signal to a process whose identifier is pid.
2. Pid =0 will signal to all processes in the same process group as the current process
3. Pid =-1 will broadcast the signal to all processes in the system
4, the pid < 0 pass the signal to the signal number of all process parameters represented by sig whose process group identification code is pid absolute value can be referred to appendix D

Return value: 0 on success or -1 on error.

Error code:
1. The EINVAL parameter sig is illegal
2. The process or process group specified by ESRCH parameter pid does not exist
3. The EPERM permission is not enough to transmit the signal to the specified process

sample


#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
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 %dn", WTERMSIG(status));
  }
}

Perform:


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


Related articles: