在操作系统课程里学习过进程间通信的方式有“管道”,“信号量”,“消息”,“共享内存”,“套接字”等。自己在学习消息过程中写了下面的测试小程序。目的是把用到的API列到这里,在需要详细了解的时候查看相关手册。
在msgServer.cc程序中,循环接收消息,把接到的消息打印出来。如果消息内容是'exit',则退出。
在msgClient.cc程序中,把命令行参数发给msgServer.cc程序。
int main()
{
key_t key;
key=560;
int queueId=msgget(key,IPC_CREAT|0600);
printf("queueId=%d/n",queueId);
if(queueId <0 ) errexit();
struct msgbuffer buf;
while(1)
{
int len=msgrcv(queueId,&buf,100,0,0);
printf("len=%d/n",len);
if(len<0) errexit();
buf.buf[len]=0;
puts(buf.buf);
if(strcmp(buf.buf,"exit")==0) break;
}
msgctl(queueId,IPC_RMID,0);
}
int main(int argc, char **argv)
{
key_t key;
key=560;
int queueId=msgget(key,0);
printf("queueId=%d/n",queueId);
if(queueId <0 ) errexit();
struct msgbuffer buf;
int i=0;
for (i=0;i<argc;i++)
{
printf("%s ",argv[i]);
strcpy(buf.buf,argv[i]);
//int len=msgsnd(queueId,&buf,strlen(argv[i])+1,0);
int len=msgsnd(queueId,&buf,100,0);
printf("len=%d/n",len);
if(len<0) errexit();
}
printf("/n");
//msgctl(queueId,IPC_RMID,0); who create, who remove it
return 0;
}