使用msgget函数创建了一个消息队列,但是函数msgget无论每次运行都是返回0.
而且在删除消息队列后再次创建时,使用ipcs -q 命令查看时,可以看到mqid是32767,但是msgget函数的返回值依然是0,并且此时消息队列无法正常收发信息,在函数msgsnd处报错individual argument。此时重启虚拟机,再次运行不会报错,mqid依然是0
#define MAX_SEND_SIZE 80
struct mymsgbuf{
long mtype;
char mtext[MAX_SEND_SIZE];
};
void send_message(int qid,struct mymsgbuf *qbuf,long type,char *text);
void read_message(int qid,struct mymsgbuf *qbuf,long type);
void remove_queue(int qid);
void change_queue_mode(int qid,char *mode);
void usage();
int main(int argc,char *argv[]){
key_t key;
int msgqueue_id;
struct mymsgbuf qbuf;
if(argc ==1)
usage();
/*Create unique key via call to ftok()*/
key = ftok(".", 2 );
if( msgqueue_id = msgget( key,IPC_CREAT | 0660) == -1){
perror("msgget\n");
exit(1);
}
printf("message queue id = [%d]\nkey = %d",msgqueue_id,key);
switch(tolower(argv[1][0]))
{
case 's':
if( argc < 4 ){
usage();
break;
}
send_message(msgqueue_id,(struct mymsgbuf*)&qbuf,atol(argv[2]),argv[3]);
break;
case 'r':
if( argc < 3 ){
usage();
break;
}
read_message(msgqueue_id,&qbuf,atol(argv[2]));
break;
case 'm':
if( argc < 3 ){
usage();
break;
}
change_queue_mode(msgqueue_id,argv[2]);
break;
case 'd':
remove_queue(msgqueue_id);
break;
default:
usage();
}
return (0);
}
void send_message(int qid,struct mymsgbuf *qbuf,long type,char *text)
{ //Send a message to the queue
printf("Sending a message ...\n");
qbuf->mtype = type;
strcpy(qbuf->mtext,text);
if((msgsnd(qid,(struct msgbuf *)qbuf,strlen(qbuf->mtext)+1,0)) == -1){
perror("msgsnd");
exit(1);
}
}
void read_message(int qid,struct mymsgbuf qbuf,long type){
//Read a message from the queue
printf("Reading a message ...\n");
qbuf->mtype = type;
msgrcv(qid,(struct msgbuf)qbuf,MAX_SEND_SIZE,type,0);
printf("Type:%ld\nText:%s\n",qbuf->mtype,qbuf->mtext);
}
void remove_queue(int qid){
msgctl(qid,IPC_RMID,0);
}
void change_queue_mode(int qid,char *mode)
{
struct msqid_ds myqueue_ds;
//Get current info
msgctl(qid,IPC_STAT,&myqueue_ds);
//Convert and load the mode
sscanf(mode,"%ho",&myqueue_ds.msg_perm.mode);
//Update the mode
msgctl(qid,IPC_SET,&myqueue_ds);
}
void usage(void)
{
fprintf(stderr,"msgtool -A utility for tinkering with msgqueues\n");
fprintf(stderr,"Usage:msgtool (s)end<type> <messagetext>\n");
fprintf(stderr,"(r)ecv <type>\n");
fprintf(stderr,"(d)elete\n");
fprintf(stderr,"(m)ode <octal mode>\n");
exit(1);
}