Hi, I trying to make a program with one thread sending a message to a message queue and the other receiving and printing it. This is what I've written so far:
When I run the program I get a bad file descriptor error in mq_send. Can anyone check the code and tell me what I'm doing wrong? Thanks.Code:#include <stdlib.h> #include <stdio.h> #include <sched.h> #include <time.h> #include <mqueue.h> #include <pthread.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #define MQUEUE_NAME "/mqueue" pthread_t send_thread, receive_thread; pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; struct timespec start_time, end_time, thread_sleep_time; mqd_t message_queue; struct mq_attr mqueue_attr; char msg = 'a'; char msg_received; unsigned int TimespecToNanosec(struct timespec tspec) { unsigned int nanosec = tspec.tv_sec * 1000000000 + tspec.tv_nsec; return(nanosec); } void* send_task() { pthread_mutex_lock(&mtx); mqueue_attr.mq_flags = 0; mqueue_attr.mq_maxmsg = 2; mqueue_attr.mq_msgsize = sizeof(msg); mqueue_attr.mq_curmsgs = 0; int flags = O_RDWR | O_CREAT; mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; printf("Opening mqueue \n"); if(mq_open(MQUEUE_NAME, flags, mode, &mqueue_attr) == -1) { perror("In mq_open "); exit(-1); } printf("Sending message \n"); if(mq_send(message_queue, (char *) &msg, sizeof(msg), 0) == -1) { perror("In mq_send()"); exit(-1); } pthread_mutex_unlock(&mtx); } void* receive_task() { pthread_mutex_lock(&mtx); printf("Receiving message \n"); if(mq_receive(message_queue, (char* ) &msg_received, mqueue_attr.mq_msgsize, 0) == -1) { perror("In mq_receive()"); } else printf("Message is: %c \n", msg_received); pthread_mutex_unlock(&mtx); } int main() { pthread_attr_t attr; struct sched_param thread_param, main_param; thread_param.sched_priority = 90; main_param.sched_priority = 80; if(sched_setscheduler(0, SCHED_FIFO, &main_param) == -1) { perror("sched_setscheduler failed"); exit(-1); } pthread_attr_init(&attr); pthread_attr_setschedpolicy(&attr, SCHED_FIFO); pthread_attr_setschedparam(&attr, &thread_param); pthread_create(&send_thread, &attr, send_task, NULL); pthread_create(&receive_thread, &attr, receive_task, NULL); pthread_join(send_thread, NULL); pthread_join(receive_thread, NULL); return(0); }



LinkBack URL
About LinkBacks


