学习apue消息队列, 想搞明白几个函数用法, 就写了一个小程序让自己感受一下IPC
发送端:
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
/*
发送端:测试IPC之消息队列有关函数
*/
#define BUFSIZE 1024
struct my_msg{
long my_type; //msg type
char my_text[BUFSIZE];
};
int main(int argc , char *argv[]){
key_t key;
int id;
int msgque_fd;
struct my_msg mymsg;
//argv is filepath and project id
if( argc != 3 )
oops( " usage : ./a.out <filepath> <id>");
id = atol( argv[2] );
// if( stat( argv[1] , &buf ) == -1)
// oops( " stat error");
/* begin to create key */
//key = ftok( argv[1] , 0x3FE);
key = ftok( argv[1] , id );
/* get msg queue fd */
// if( ( msgque_fd = msgget( key , IPC_PRIVATE) )
if( ( msgque_fd = msgget( key , IPC_CREAT ) )
== -1 )
oops( " msgget" );
else
printf( "msgque_fd=%d.\n" , msgque_fd );
//send data
while(1){
/* get data from stdin */
printf( "type text which you want to send:\n" );
fgets( mymsg.my_text , BUFSIZE , stdin);
/* create my_msg */
mymsg.my_type = 1;
/* send text */
if( msgsnd( msgque_fd , &mymsg , BUFSIZE , 0 )
== -1 )
oops( " msgsnd " );
}
return 0;
}
接收端:
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
/*
接收端:测试IPC之消息队列有关函数
*/
#define BUFSIZE 1024
struct my_msg{
long my_type; //msg type
char my_text[BUFSIZE];
};
int main(int argc , char *argv[]){
key_t key;
int id;
int msgque_fd , n;
struct my_msg mymsg;
//argv is filepath and project id
if( argc != 3 )
oops( " usage : ./a.out <filepath> <id>");
id = atol( argv[2] );
// if( stat( argv[1] , &buf ) == -1)
// oops( " stat error");
/* begin to create key */
//key = ftok( argv[1] , 0x3FE);
key = ftok( argv[1] , id );
/* get msg queue fd */
// if( ( msgque_fd = msgget( key , IPC_PRIVATE) )
if( ( msgque_fd = msgget( key , IPC_CREAT ) )
== -1 )
oops( " msgget" );
else
printf( "msgque_fd=%d.\n" , msgque_fd );
//send data
while(1){
/* recv text */
if( (n = msgrcv( msgque_fd , &mymsg , BUFSIZE , 0
,0) ) == -1)
oops( " msgrcv");
/* show recv text */
printf( "recv msg: %s.\n" ,mymsg.my_text );
}
return 0;
}
注: 1.另外两篇文章说的很好http://blog.csdn.net/jiajiayouba/article/details/8815042和http://blog.chinaunix.net/uid-30510400-id-5476962.html
2.使用ftok 创建key,搞不明白为什么要用一个路径,还必须exist
3.使用msgget 不明白为什么要用0664|IPC_CREAT ,还有就是只用IPC_PRIVATE 出现:http://bbs.csdn.net/topics/90168236这个错误
4. 要用sudo ,估计是权限问题, 我还没有学习msgctl函数,最近太忙了, 以后再回来研究