c - Sending signals between three threads -
i had write program uses 3 threads - 1 read letters, second count characters, , third output them. code:
#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <unistd.h> #include <linux/stat.h> #include <pthread.h> #include <string.h> #include <signal.h> int first[2]; int second[2]; void *input(void *ptr) { char str[100]; int length; while(1) { printf("enter message: "); fflush(stdout); length = read(stdin_fileno, str, sizeof(str)); if(str[0] == ';') exit(2); if(length <= 0) { if(length == -1) perror("read"); close(first[1]); exit(2); } if(write(first[1], str, length) != length) { perror("write"); exit(2); } } } void *countchars(void *ptr) { char str[100]; int length, count = 0; while(1) { length = read(first[0], str, sizeof(str)); if(length <= 0) { if(length == -1) perror("read"); close(first[0]); close(second[1]); exit(2); } if(write(stdout_fileno, str, length) != length) { perror("write"); exit(2); } while(str[count] != '\n') count++; write(second[1], &count, sizeof(count)); count = 0; } } void *output(void *ptr) { int length, count = 0; while(1) { length = read(second[0], &count, sizeof(count)); if(length < sizeof(count)) { close(second[0]); exit(2); } printf("number of characters: %d\n", count); } } int main() { pthread_t t1, t2, t3; if(pipe(first) == -1) { printf("first pipe error"); exit(1); } if(pipe(second) == -1) { printf("second pipe error"); exit(1); } pthread_create(&t1, null, input, null); pthread_create(&t2, null, countchars, null); pthread_create(&t3, null, output, null); pthread_join(t1, null); pthread_join(t2, null); pthread_join(t3, null); return 0; } it works, right have implement signals here. sending sigusr1 signal should stop program execution until sending sigusr2 signal.
the problem when send signal, 1 thread gets it. , have use fifo inform other threads signal executed , execute in rest of them.
how this?
signals delivered process, not threads. thread able handle signal may used call signal handler. need figure out how handle signal , decide how communicate threads. have not described mean "stop program execution", i'll have guess.
i suggest using combination of pthread_sigmask , sigwait. can use pthread_sigmask disable automatic handling of sigusr1 , sigusr2 in worker threads. call sigwait in fourth signal handler thread explicitly handle signals. when signal handler thread receives sigusr1 sets global flag. worker threads check flag periodically , go sleep (on condition variable maybe?) when set. signal handler thread loops around , calls sigwait again. when receives sigusr2, wakes worker threads, loops around , calls sigwait, once again.
Comments
Post a Comment