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

C Library Function – sigwait()

C Library Function - sigwait()

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

Description

sigwait The function is a function in the C standard library, used to synchronously wait for the arrival of a signal. It removes one of the signals from the specified signal set out of the queue and returns its number. This function is defined in header.

Syntax

int sigwait(const sigset_t *set, int *sig);

Parameters

Return Value

Example

The following is an example of using sigwait Example of the function synchronously waiting for SIGINT signal. The program prints a message while waiting for the signal, and when a SIGINT signal is caught, uses the sigwait The function synchronously waits for and handles signals.

Example

#include

#include

#include

#include

// thread function, waiting for the SIGINT signal

void

wait_for_signal

(

void

arg

)

{

    sigset_t

set

=

(

sigset_t

)

arg

;

   

int

sig

;

   

printf

(

"Thread waiting for signal...\n"

)

;

   

if

(

sigwait

(

set

,

&

sig

)

==

0

)

{

       

printf

(

"Caught signal %d: %s\n"

,

sig

,

strsignal

(

sig

)

)

;

   

}

else

{

       

perror

(

"sigwait"

)

;

   

}

   

return

NULL

;

}

int

main

(

)

{

    pthread_t thread

;

    sigset_t set

;

   

// initialize the signal set and add SIGINT to the signal set

    sigemptyset

(

&

set

)

;

    sigaddset

(

&

set

,

SIGINT

)

;

   

// block the SIGINT signal in the main thread

    pthread_sigmask

(

SIG_BLOCK

,

&

set

,

NULL

)

;

   

// create a thread to wait for the SIGINT signal

    pthread_create

(

&

thread

,

NULL

,

wait_for_signal

,

(

void

)

&

set

)

;

   

// the main thread continues to run until Ctrl+C is pressed to send the SIGINT signal

   

while

(

1

)

{

       

printf

(

"Main thread running... Press Ctrl+C to send SIGINT\n"

)

;

        sleep

(

1

)

;

   

}

   

// wait for the child thread to finish

    pthread_join

(

thread

,

NULL

)

;

   

return

0

;

}

After compiling and running the program, press Ctrl+C to send SIGINT signal, and the output will be:

Main thread running... Press Ctrl+C to send SIGINT

Main thread running... Press Ctrl+C to send SIGINT

Main thread running... Press Ctrl+C to send SIGINT

Thread waiting for signal...

Caught signal 2: Interrupt

The program blocks SIGINT signal in the main thread and creates a child thread to wait for and handle SIGINT signal. When the SIGINT signal is caught, the child thread uses sigwait The function synchronously waits for and handles signals.

Explanation

Notes

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