1.Callback函数与共享内存方式结合:符合第三方黑盒子调用。
2. 适应与多方合作开发。
//test_callback.h
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/shm.h>
#include "shmdata.h"
#include <cstring>
using namespace std;
//-----------------------底层实现A-----------------------------
typedef void (*pcb)(char *s); //函数指针定义,后面可以直接使用pcb,方便
typedef struct parameter{
char text[2048];//记录写入和读取的文本
pcb callback;
}parameter;
//留给应用层B的接口函数
void init();
bool read();
void* callback_thread(void *p1);
extern void SetCallBackFun(const char *s, pcb callback);
//test_callback.cpp
#include "test_acallback.h"
#define SHARE_ID 1234
struct shared_use_st *shared;//指向shm
void init()
{
void *shm = NULL;//分配的共享内存的原始首地址
int shmid;//共享内存标识符
//创建共享内存
shmid = shmget((key_t)SHARE_ID, sizeof(struct shared_use_st), 0666|IPC_CREAT);
if(shmid == -1)
{
fprintf(stderr, "shmget failed\n");
exit(EXIT_FAILURE);
}
shm = shmat(shmid, 0, 0);
if(shm == (void*)-1)
{
fprintf(stderr, "shmat failed\n");
exit(EXIT_FAILURE);
}
printf("\nMemory attached at %X\n", (long)shm);
//设置共享内存
shared = (struct shared_use_st*)shm;
}
bool read()
{
bool ret = false;
if(shared->written != 0)
{
printf("You wrote: %s", shared->text);
sleep(rand() % 3);
//读取完数据,设置written使共享内存段可写
shared->written = 0;
return true;
}else
{
return false;
}
}
void* callback_thread(void *p1)//此处用的是一个线程
{
//do something
parameter* p = (parameter*)p1 ;
init();
while(1)
{
//printf("GetCallBack print! \n");
if(true == read())
{
sprintf(p->text,"%s",shared->text);
printf("GetCallBack print=%s\n\n",p->text);
p->callback(p->text);//函数指针执行函数,这个函数来自于应用层B
}
else
{
sleep(1);
continue;
}
sleep(1);//延时3秒执行callback函数
}
}
extern void SetCallBackFun(const char *s, pcb callback)
{
printf("SetCallBackFun print! \n");
parameter *p = (parameter*)malloc(sizeof(parameter)) ;
sprintf(p->text,"%s",s);
p->callback = callback;
//创建线程
pthread_t thing1;
pthread_create(&thing1,NULL,callback_thread,(void *) p);
pthread_join(thing1,NULL);
}
//test_bcallback.cpp
#include <stdio.h>
#include <cstring>
#include "test_acallback.h"
using namespace std;
//-----------------------应用者B-------------------------------
void fCallBack( char *s) // 应用者增加的函数,此函数会在A中被执行
{
//do something
printf("tty_best = %s\n",s);
printf("fCallBack print!\n");
}
int main(void)
{
SetCallBackFun("start",fCallBack);
return 0;
}