Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <fcntl.h>
- #include <pthread.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <string.h>
- #include <mqueue.h>
- using namespace std;
- typedef struct Arguments {
- bool* flag;
- timespec* tm;
- mqd_t* mqid;
- } arguments;
- void *thread(void *args) {
- puts("read thread started");
- arguments *argument = (arguments*) args;
- (*(argument->tm)).tv_sec = 0;
- (*(argument->tm)).tv_nsec = 100000000;
- char buf[100];
- while (*(argument->flag)) {
- while ((mq_receive(*(argument->mqid), buf, 100, 0)) <= 0) {
- if (!*(argument->flag))
- return 0;
- nanosleep(argument->tm, NULL);
- }
- printf("Readed: %s\n", buf);
- fflush(stdout);
- sleep(1);
- }
- printf("read thread finished");
- fflush(stdout);
- pthread_exit(NULL);
- }
- int main() {
- char mq_name[] = "/message_queue";
- bool flag = true;
- pthread_t threadInit;
- arguments args;
- mq_attr attr;
- timespec tm;
- mqd_t mqid;
- tm.tv_sec = 0;
- tm.tv_nsec = 100000000;
- attr = {O_NONBLOCK, 10, 64, 0};
- mqid = mq_open(mq_name, O_CREAT | O_RDONLY | O_NONBLOCK, 0777, &attr);
- args.flag = &flag;
- args.tm = &tm;
- args.mqid = &mqid;
- if(pthread_create(&threadInit, NULL, &thread,(void*) &args))
- return EXIT_FAILURE;
- getchar();
- flag = false;
- pthread_join(threadInit, NULL);
- mq_close(mqid);
- mq_unlink(mq_name);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment