在阅读项目系统底层代码时,看到使用的IPC消息队列是Posix的,之前自己使用的是system V 消息队列,两者在某些方面还是有部分区别的。
底层在设计的时候,是先根据上层传入的消息队列名字,删除这个消息队列,然后再去创建消息队列:
mq_unlink(strName);
que = mq_open(strName, oflag, mode, &attr);
在开发固件项目软件的过程中,发现很多使用C语言的高手和前辈写的优秀的代码,真的是很佩服,并且他们的在使用面向对象的设计理念来把C语言使用到了极致,真的是太牛了,就像PM说的,你以为没有学习的余地,其实是你不想努力而已,就是自己不优秀,又不想学习,并且还不想坚持。
做了一个demon程序:
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<errno.h>
#define TRUE 1
#define FALSE 0
#define MAX 4
#define MSGKEY 1024
int msqid;
typedef struct msgstru
{
long msgtype;
char msgtext[2048];
}MSGS;
void *ThreadProbe(void * arg)
{
int ret_value;
MSGS msgs;
printf("%s\n",(char *)arg);
printf("this is call back function\n");
while(1)
{
ret_value = msgrcv(msqid,&msgs,sizeof(MSGS),0,0);
printf("text=[%s] pid = %d\n",msgs.msgtext,getpid());
sleep(3);
}
}
int CreateThread(void)
{
pthread_t tid;
if(pthread_create(&tid, NULL, ThreadProbe, "Hello world") != 0)
{
return FALSE ;
}
printf("%s:tid:%d\n",__FILE__,getpid());
return TRUE ;
}
int main(void)
{
int ret = 0;
int i = 0;
MSGS msgs;
int msg_type;
char str[256];
int ret_value;
msqid = msgget(MSGKEY,IPC_CREAT|0666);
if(msqid < 0)
{
printf("failed to create msq | errno=%d [%s]\n",errno,strerror(errno));
exit(-1);
}
ret = CreateThread();
if(FALSE == ret)
{
printf("create thread fail\n");
}
else
{
printf("%s:create new thread success\n",__FILE__);
}
while(1)
{
printf("please input send message\n");
scanf("%s",str);
strcpy(msgs.msgtext,str);
ret_value = msgsnd(msqid,&msgs,sizeof(struct msgstru),IPC_NOWAIT);
if(ret_value < 0)
{
printf("msgsnd() write msg failed,errno=%d[%s]\n",errno,strerror(errno));
exit(-1);
}
sleep(2);
}
return 0;
}
因为看到很多一提到消息队列,大部分举例的都是进程与进程之间的使用,很少又说到两个线程之间使用消息队列来进行数据交互的,因为线程之间数据交互比较容易,使用全局变量,其实这个demon也是使用全局变量的形式,就是说使用全局的消息队列ID,感觉这样的优点是控制起来更加的明了,因为线程之间的交互是点对点的。