看了下网上的代码,发现XSI和POSIX的API形式不同,一开始没摸着头脑。这里忠于apue,用XSI进行实验。
后来又遇到了一些奇怪的问题,陆续会写上来。
----------------------------------------------
堆栈溢出问题没有复现,代码没备份,因此也不知道原因为何。。
下面是两个进程消息队列通信的例子。
创建队列:
- #include <stdio.h>
-
#include <sys/msg.h>
-
#include <sys/ipc.h>
-
-
int main(void)
-
{
-
int id;
-
id = msgget(IPC_PRIVATE, IPC_CREAT|0660);
-
printf("\n%d\n", id);
-
return 0;
-
}
发送进程:
- #include <stdio.h>
-
#include <sys/msg.h>
-
#include <sys/ipc.h>
-
-
int main(void)
-
{
-
int id;
-
id = msgget(IPC_PRIVATE, IPC_CREAT|0660);
-
printf("\n%d\n", id);
-
return 0;
-
}
-
-
lisong@lisong:~/code/experiment/proc/IPC/msgqueue$
-
lisong@lisong:~/code/experiment/proc/IPC/msgqueue$
-
lisong@lisong:~/code/experiment/proc/IPC/msgqueue$
-
lisong@lisong:~/code/experiment/proc/IPC/msgqueue$ more msgqs.c
-
#include <stdio.h>
-
#include <sys/msg.h>
-
#include <sys/ipc.h>
-
-
typedef struct mymsg{
-
long msgtype;
-
char mdata[100];
-
}msg_t;
-
-
int main(int argc, char *argv[])
-
{
-
int ret;
-
int msgq_id;
-
char *msgstr;
-
msg_t msg;
-
-
if(argc < 3)
-
{
-
printf("please run this with msgqueue id and msgbody.\n");
-
return -1;
-
}
-
msgq_id = atoi(argv[1]);
-
if(msgq_id < 0)
-
{
-
printf("wrong queue id:%d.\n", msgq_id);
-
return -2;
-
}
-
printf("msgq_id:%d.\n", msgq_id);
-
msgstr = argv[2];
-
memset(&msg, 0, sizeof(msg));
-
msg.msgtype = 1;
-
strcpy(msg.mdata, msgstr);
-
ret = msgsnd(msgq_id, &msg, strlen(msg.mdata), IPC_NOWAIT);
-
printf("ret:%d.\n", ret);
-
return 0;
-
}
接收进程:
- #include <stdio.h>
-
#include <sys/msg.h>
-
#include <sys/ipc.h>
-
-
typedef struct mymsg{
-
long msgtype;
-
char mdata[100];
-
}msg_t;
-
-
int main(int argc, char *argv[])
-
{
-
int s;
-
int msgq_id;
-
msg_t msg;
-
-
if(argc < 2)
-
{
-
printf("please run with msgqueue id.\n");
-
return -1;
-
}
-
msgq_id = atoi(argv[1]);
-
if(msgq_id < 0)
-
{
-
printf("wrong queue id:%d.\n", msgq_id);
-
return -2;
-
}
-
memset(&msg, 0, sizeof(msg));
-
printf("sizeof(msg):%d.\n", sizeof(msg));
-
s = msgrcv(msgq_id, &msg, 100, 0, IPC_NOWAIT);
-
printf("s:%d,msg.mdata:%s.\n", s, msg.mdata);
-
return 0;
-
}
阅读(1429) | 评论(0) | 转发(0) |