#blognavi
pthreadでスレッドを作って、メッセージを飛ばして、
応答を取得するサンプル
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <sys/types.h>
#define BUFSIZE 32
struct mymsg {
int id;
char com[BUFSIZE];
};
/* message struct */
struct msgbuf {
long int type;
struct mymsg data;
};
/* global */
key_t msgkey;
int msgQID_com;
int msgQID_res;
void *test_thread(void *param)
{
struct msgbuf message = {0};
printf("pid=%d\n", getpid() );
while(1){
if( msgrcv(msgQID_com, &message, sizeof(message.data), 0, 0) == -1 ){
printf("msgrcv err\n");
exit(1);
}
printf("message rcv: id=%d data=%s\n", message.data.id, message.data.com);
/* send reply */
message.data.id = 2;
strncpy( message.data.com, "resp1", BUFSIZE );
if( msgsnd(msgQID_res, &message, sizeof(message.data), 0) == -1 ){
printf("msgsnd err\n");
exit(1);
}
break;
}
return param;
}
int main(void)
{
int status;
pthread_t test;
struct msgbuf message;
struct msgbuf reply;
printf("parent pid=%d\n", getpid() );
/* set message */
message.type = getpid();
message.data.id = 1;
strncpy( message.data.com, "command1", BUFSIZE );
/* get message queue */
msgkey = 1111;
if( (msgQID_com = msgget( msgkey, 0666|IPC_CREAT) ) == -1 ){
printf("msgget err\n");
exit(1);
}
msgkey = 2222;
if( (msgQID_res = msgget( msgkey, 0666|IPC_CREAT) ) == -1 ){
printf("msgget err\n");
exit(1);
}
/* create thread */
status = pthread_create( &test, NULL, test_thread, NULL );
if( status != 0 ){
printf("thread create err\n");
exit(1);
}
/* message send */
if( msgsnd(msgQID_com, &message, sizeof(message.data), 0) == -1 ){
printf("msgsnd err\n");
exit(1);
}
/* rcv resp */
if( msgrcv(msgQID_res, &reply, sizeof(reply.data), 0, 0) == -1 ){
printf("msgrcv err\n");
exit(1);
}
printf("reply data: id=%d data=%s\n", reply.data.id, reply.data.com);
/* join thread */
status = pthread_join( test, NULL );
if( status != 0 ){
printf("thread join err\n");
exit(1);
}
return 0;
}
ビルドする際には、
gcc -Wall pthread_test.c -lpthread
カテゴリ: [
日記] - &trackback() - 2015年10月18日 00:09:13
#blognavi
最終更新:2015年10月18日 00:17