Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Function - sigaction()

C Library Function - sigaction()

C Standard Library - <signal.h> C Standard Library -

sigaction is a function in the C standard library used to inspect or modify the action associated with a specific signal. Compared with signal function,sigaction provides more control and better portability.

Syntax

int sigaction(int sig, const struct sigaction *act, struct sigaction *oldact);

Parameters

struct sigaction Structure

struct sigaction {

    void (*sa_handler)(int);           // 信号处理函数指针

    void (*sa_sigaction)(int, siginfo_t *, void *); // 信号处理函数指针(扩展)

    sigset_t sa_mask;                  // 在处理该信号时要阻塞的信号集

    int sa_flags;                      // 修改信号行为的选项

    void (*sa_restorer)(void);         // 恢复函数,已废弃

};

sa_flags common options

Return Value

Example

The following is a simple example program demonstrating how to use the sigaction The function sets SIGINT the handler for the signal:

Example

#include

#include

#include

// Custom signal handler function

void

handle_sigint

(

int

sig

)

{

   

printf

(

"Caught signal %d\n"

,

sig

)

;

}

int

main

(

)

{

   

struct

sigaction sa

;

   

// Set the handler to handle_sigint

    sa.

sa_handler

=

handle_sigint

;

    sigemptyset

(

&

sa.

sa_mask

)

;

    sa.

sa_flags

=

0

;

   

// Use sigaction to set the new signal-handling action

   

if

(

sigaction

(

SIGINT

,

&

sa

,

NULL

)

==

1

)

{

       

perror

(

"sigaction"

)

;

       

return

1

;

   

}

   

// Main loop, running continuously until a signal is caught

   

while

(

1

)

{

       

printf

(

"Running...\n"

)

;

        sleep

(

1

)

;

   

}

   

return

0

;

}

After compiling and running the program, the output will be:

Running...

Running...

Running...

...

When Ctrl+C is pressed (sending a SIGINT signal), the output will be:

Caught signal 2

The program catches the SIGINT signal and executes the custom signal handler handle_sigint, then continues running the main loop.

Notes

C Standard Library - <signal.h> C Standard Library -