Вот решил накропать Hello/bye world на Ц. Почитал ман по sleep
sleep() makes the calling thread sleep until seconds seconds have elapsed or a signal arrives which is not ignored.
И в соотвецтвии с маном сгенерил код который даже компилится (у меня у вас может и нет):
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
time_t startTime;
void dbg(const char *msg)
{
printf("[%03i 0x%08x] %s\n", (int)(time(NULL) - startTime), (int)(pthread_self()), msg);
}
void* thread2(void *p)
{
dbg("Sleep in TH2");
sleep(20);
return NULL;
}
void onSigAlarm(int sigNum)
{
dbg("Sig alaram received");
}
int main(int argc, char* argv[])
{
pthread_t th2;
startTime = time(NULL);
dbg("Hello World");
signal(SIGALRM, onSigAlarm);
pthread_create(&th2, NULL, thread2, NULL);
sleep(1);
kill(getpid(), SIGALRM);
dbg("Wait for TH2 ...");
pthread_join(th2, NULL);
dbg("bye!");
return 0;
}
kill(getpid(), SIGALRM);
[000 0x9f723700] Hello World
[000 0x9ef81700] Sleep in TH2
[001 0x9f723700] Sig alaram received
[001 0x9f723700] Wait for TH2 ...
[020 0x9f723700] bye!
С другой стороны «Hello/Bye world V2.0.0» работает так как написано в мане.
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
time_t startTime;
void dbg(const char *msg)
{
printf("[%03i 0x%08x] %s\n", (int)(time(NULL) - startTime), (int)(pthread_self()), msg);
}
void* thread2(void *p)
{
dbg("Hello from TH2");
sleep(1);
dbg("Sending SIGALRM ...");
kill(getpid(), SIGALRM);
return NULL;
}
void onSigAlarm(int sigNum)
{
dbg("Sig alaram received");
}
int main(int argc, char* argv[])
{
pthread_t th2;
startTime = time(NULL);
dbg("Hello World");
signal(SIGALRM, onSigAlarm);
pthread_create(&th2, NULL, thread2, NULL);
dbg("Sleep in TH1");
sleep(20);
dbg("Wait for TH2 ...");
pthread_join(th2, NULL);
dbg("bye!");
return 0;
}
[000 0xe6fa6700] Hello World
[000 0xe6fa6700] Sleep in TH1
[000 0xe6804700] Hello from TH2
[001 0xe6804700] Sending SIGALRM ...
[001 0xe6fa6700] Sig alaram received
[001 0xe6fa6700] Wait for TH2 ...
[001 0xe6fa6700] bye!
Поскольку гуглить было жутко влом, я в продакшен проекте поменял sleep на conditional variable (соотвецтвенно kill сменил на нотифай) - но вопрос остался открытым как рулить sleep через SIGALARM для не основного потока ?