/* * Przykładowy program dla kursu "POSIX Threads" z wikibooks.pl * * Temat: wysyłanie sygnałow UNIX-owych do wątków * * Autor: Wojciech Muła * Ostatnia zmiana: 2010-03-xx */
#define _POSIX_C_SOURCE 200809L#include<stdlib.h>#include<stdio.h>#include<errno.h>#include<pthread.h>#include<signal.h>#include<unistd.h> // sleep#define test_errno(msg) do{if (errno) {perror(msg); exit(EXIT_FAILURE);}} while(0)pthread_tmain_id;// id głównego wątek// funkcja wątkuvoid*watek(void*nieuzywany){puts("\twątek się rozpoczął");sleep(1);puts("\twątek wysyła sygnał SIGUSR1 do głównego wątku");errno=pthread_kill(main_id,SIGUSR1);test_errno("pthread_kill");returnNULL;}//------------------------------------------------------------------------intmain(){pthread_tid;intsignum;sigset_tmask;// blokowanie SIGUSR1sigemptyset(&mask);sigaddset(&mask,SIGUSR1);errno=pthread_sigmask(SIG_BLOCK,&mask,NULL);test_errno("pthread_kill");// odczyt id głównego wątkumain_id=pthread_self();// utworzenie wątkuerrno=pthread_create(&id,NULL,watek,NULL);test_errno("pthread_create");// oczekiwanie na sygnałputs("wątek główny oczekuje na sygnał");sigwait(&mask,&signum);test_errno("sigwait");if(signum==SIGUSR1)puts("wątek główny otrzymał sygnał SIGUSR1");elseprintf("wątek główny otrzymał sygnał %d\n",signum);returnEXIT_SUCCESS;}//------------------------------------------------------------------------