// mtype: // 1 - client -> server // 2 - server -> client int main( int argc, char** argv ) { int idx=0; int mq_id=-1; char seed = 'A'; static struct mq_message_s mq_message; // init memset( mq_message.content, '\0', MQ_MESSAGESIZ ); memset( mq_message.content_name, '\0', MQ_NAMESIZE ); strcpy( mq_message.content_name, "test" ); mq_message.content_type = MQDATA_STRING; mq_message.needs_confirmation = 0; mq_message.arr_extent = strlen( TEXT ) + 1; strcpy( mq_message.content, TEXT ); // init if( ERRCODE_SUCCESS != _mq_init( &mq_id, seed ) ){ perror( "_mq_init()" ); exit( ERRCODE_FAILURE ); } do{ ++idx; // send hello fprintf( stderr, "send \"%s\"\n", mq_message.content ); mq_message.mtype = 1; if( ERRCODE_SUCCESS != _mq_send( mq_id, &mq_message, mq_message.mtype, 0 ) ){ perror( "_mq_send() failed" ); } sleep( 1 ); // receive hello mq_message.mtype = 2; memset( mq_message.content, '\0', MQ_MESSAGESIZ ); fprintf( stderr, "cleared \"%s\"\n", mq_message.content ); _mq_retrieve( mq_id, &mq_message, mq_message.mtype, 0 ); fprintf( stderr, "received \"%s\"\n", ( (strlen( mq_message.content ) > 0) ? mq_message.content : "nothing" ) ); }while( 3 > idx ); exit( EXIT_SUCCESS ); }
static int _mq_connect(struct ipc *ipc, const char *name) {//for client struct mq_ctx *ctx = ipc->ctx; struct mq_attr attr; ctx->parent = ipc; attr.mq_flags = 0; attr.mq_maxmsg = MQ_MAXMSG; attr.mq_msgsize = MQ_MSGSIZE; attr.mq_curmsgs = 0; int wflag = O_WRONLY | O_EXCL; ctx->mq_wr = mq_open(name, wflag, S_IRWXU | S_IRWXG, &attr); if (ctx->mq_wr < 0) { loge("mq_open %s failed: %d:%s\n", name, errno, strerror(errno)); return -1; } strncpy(ctx->mq_wr_name, name, sizeof(ctx->mq_wr_name)); if (0 > _mq_send(ipc, ctx->mq_rd_name, strlen(ctx->mq_rd_name))) { loge("_mq_send failed!\n"); return -1; } struct timeval now; struct timespec abs_time; uint32_t timeout = 5000;//msec gettimeofday(&now, NULL); /* Add our timeout to current time */ now.tv_usec += (timeout % 1000) * 1000; now.tv_sec += timeout / 1000; /* Wrap the second if needed */ if ( now.tv_usec >= 1000000 ) { now.tv_usec -= 1000000; now.tv_sec ++; } /* Convert to timespec */ abs_time.tv_sec = now.tv_sec; abs_time.tv_nsec = now.tv_usec * 1000; if (-1 == sem_timedwait(&ctx->sem, &abs_time)) { loge("connect %s failed %d: %s\n", name, errno, strerror(errno)); return -1; } return 0; }
static int _mq_accept(struct ipc *ipc) {//for server struct mq_ctx *ctx = ipc->ctx; ctx->parent = ipc; struct mq_attr attr; attr.mq_flags = 0; attr.mq_maxmsg = MQ_MAXMSG; attr.mq_msgsize = MQ_MSGSIZE; attr.mq_curmsgs = 0; sem_wait(&ctx->sem); ctx->mq_wr = mq_open(ctx->mq_wr_name, O_WRONLY, S_IRWXU | S_IRWXG, &attr); if (ctx->mq_wr < 0) { loge("mq_open %s failed: %d:%s\n", ctx->mq_wr_name, errno, strerror(errno)); return -1; } if (0 > _mq_send(ipc, ctx->mq_wr_name, strlen(ctx->mq_wr_name))) { loge("_mq_send failed!\n"); return -1; } return 0; }