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

C Library Function – sigsuspend()

C Library Function - sigsuspend()

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

sigsuspend The function is a function in the C standard library, used to temporarily replace the current signal mask and suspend the process until a signal is caught. It is often used to implement atomic signal waiting, that is, no signals are lost while waiting.

Syntax

int sigsuspend(const sigset_t *mask);

Parameters

Return Value

Example

The following is an example of using sigsuspend Example program demonstrating the function waiting for a specific signal. The program sets up a signal handler and then uses sigsuspend to suspend the process until a signal is caught.

Example

#include

#include

#include

volatile

sig_atomic_t flag

=

0

;

// Custom signal handler function

void

handle_sigint

(

int

sig

)

{

   

printf

(

"Caught signal %d\n"

,

sig

)

;

    flag

=

1

;

}

int

main

(

)

{

   

struct

sigaction sa

;

    sigset_t new_mask

,

old_mask

,

wait_mask

;

   

// set the handler for SIGINT to handle_sigint

    sa.

sa_handler

=

handle_sigint

;

    sigemptyset

(

&

sa.

sa_mask

)

;

    sa.

sa_flags

=

0

;

   

if

(

sigaction

(

SIGINT

,

&

sa

,

NULL

)

==

1

)

{

       

perror

(

"sigaction"

)

;

       

return

1

;

   

}

   

// initialize the signal set

    sigemptyset

(

&

new_mask

)

;

    sigaddset

(

&

new_mask

,

SIGINT

)

;

   

// block the SIGINT signal

   

if

(

sigprocmask

(

SIG_BLOCK

,

&

new_mask

,

&

old_mask

)

==

1

)

{

       

perror

(

"sigprocmask"

)

;

       

return

1

;

   

}

   

// initialize the wait signal set

    sigemptyset

(

&

wait_mask

)

;

   

printf

(

"Waiting for SIGINT...\n"

)

;

   

// use sigsuspend to suspend the process and wait for a signal

   

while

(

!

flag

)

{

       

if

(

sigsuspend

(

&

wait_mask

)

!=

1

)

{

           

perror

(

"sigsuspend"

)

;

           

return

1

;

       

}

   

}

   

// restore the original signal mask

   

if

(

sigprocmask

(

SIG_SETMASK

,

&

old_mask

,

NULL

)

==

1

)

{

       

perror

(

"sigprocmask"

)

;

       

return

1

;

   

}

   

printf

(

"Exiting...\n"

)

;

   

return

0

;

}

Assuming the program is compiled and run, the output will be:

Waiting for SIGINT...

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

Caught signal 2

Exiting...

The program catches the SIGINT signal, the signal handler was executed handle_sigint, setting flag to 1, causing the main loop to terminate and the program to exit.

Explanation

Notes

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