Created
December 8, 2019 16:22
-
-
Save MinatsuT/294706a3ca6029391a9650f344b00ab4 to your computer and use it in GitHub Desktop.
pthread と sigaction の最小サンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* pthread と sigaction の最小サンプル by みなつ | |
* | |
* gcc -o pthread_sample1 -lpthread pthread_sample1.c | |
* | |
*/ | |
#include <pthread.h> | |
#include <signal.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
// シグナルハンドラ | |
volatile sig_atomic_t main_run_flag = 1; | |
void sigintHandler(int sig) { main_run_flag = 0; } | |
// スレッド | |
volatile int th_run_flag = 1; | |
void *thRun(void *arg) { | |
int cnt = 0; | |
while (th_run_flag) { | |
printf("子:%d\n", cnt++); | |
sleep(1); | |
} | |
puts("子:終了"); | |
return NULL; | |
} | |
int main(int argc, char *argv[]) { | |
// シグナルハンドラの設定 | |
struct sigaction sa; | |
memset(&sa, 0, sizeof(sa)); | |
sa.sa_handler = sigintHandler; | |
if (sigaction(SIGINT, &sa, NULL) < 0) { | |
perror("シグナルハンドラ登録失敗(´;ω;`)"); | |
return 1; | |
} | |
// スレッドの作成・開始 | |
pthread_t th; | |
if (pthread_create(&th, NULL, thRun, NULL) != 0) { | |
perror("スレッド作成失敗(´;ω;`)"); | |
return 1; | |
} | |
// メインループ | |
while (main_run_flag) { | |
puts("親:ほげー"); | |
sleep(5); | |
} | |
puts(""); | |
// 終了処理 | |
puts("親:スレッド終了待ち"); | |
th_run_flag = 0; | |
if (pthread_join(th, NULL) != 0) { | |
perror("スレッドjoin失敗(´;ω;`)"); | |
return 1; | |
} | |
puts("親:終了"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment