想建立一个socket连接池,管理设备通讯的长连接。想到使用链表的数据结构。后期增加数据库连接池。
先写个简单的链表管理,功能如下:
1. 创建链表
2. 销毁链表
3. 取出节点
4. 恢复节点
代码如下:
#include <stdio.h>
#include <stdlib.h>
#define NODECOUNT 10
#ifdef DUMP
#define DBGDATA(fmt, pstr) \
fprintf (stderr, "\n c === FUNC[%s] | LINE[%d] | " #pstr "["fmt"] ===\n" ,__func__, __LINE__, pstr)
#else
#define DBG_DUMP(fmt, pstr)
#endif
typedef struct listnode
{
int ihandle;
int istatus;
struct listnode *next;
}stuHandle;
void printlist(stuHandle *phead);
stuHandle *DestroyOneNode(stuHandle *pnode)
{
stuHandle *pn = pnode->next;
free(pnode);
return pn;
}
stuHandle *DestroyList(stuHandle *phead)
{
stuHandle *ph = phead;
stuHandle *pn = NULL;
while (ph != NULL)
{
ph = DestroyOneNode(ph);
}
return NULL;
}
stuHandle *CreatOneNode(void)
{
stuHandle *ptmp = NULL;
ptmp = (stuHandle *)malloc(sizeof(stuHandle));
if (NULL == ptmp)
{
return NULL;
}
ptmp->ihandle = -1;
ptmp->istatus = 0;
ptmp->next = NULL;
return ptmp;
}
stuHandle *CreatNode(int inodenum)
{
stuHandle *phead = NULL;
stuHandle *pnode = NULL;
stuHandle *ptmp = NULL;
int i = 0;
if (inodenum <= 0)
{
return NULL;
}
phead = pnode = CreatOneNode();
if (NULL == pnode)
{
return NULL;
}
for (i=1;i<inodenum;i++)
{
ptmp = CreatOneNode();
if (NULL == ptmp)
{
return DestroyList(phead);
}
#ifdef DUMP
ptmp->ihandle = -(i + 1);
#endif
pnode->next = ptmp;
pnode = pnode->next;
}
return phead;
}
stuHandle *GetOneNode(stuHandle **phead)
{
stuHandle *ptmp;
if (NULL == phead)
{
return NULL;
}
ptmp = *phead;
*phead = (*phead)->next;
ptmp->next = NULL;
return ptmp;
}
stuHandle *ResumeOneNode(stuHandle **phead, stuHandle *pnode)
{
stuHandle *ptmp = NULL;
stuHandle *ps = NULL;
ptmp = *phead;
if (NULL == pnode)
{
return NULL;
}
if (NULL == ptmp)
{
*phead = pnode;
(*phead)->next = NULL;
return *phead;
}
while (ptmp->next != NULL)
{
ptmp = ptmp->next;
}
ptmp->next = pnode;
return *phead;
}
void printlist(stuHandle *phead)
{
stuHandle *ptmp = phead;
int i = 0;
fprintf (stderr, "\n");
while (ptmp != NULL)
{
fprintf (stderr, "node id[%d] == node ptr[0x%x] == ihandle[%d] == istatus[%d] == node next ptr[0x%x]\n",
i++, ptmp, ptmp->ihandle, ptmp->istatus, ptmp->next);
ptmp = ptmp->next;
}
fprintf (stderr, "\n");
}
int main(int argc, char **argv)
{
stuHandle *phead = NULL;
stuHandle *(p[10]);
int i = 0;
phead = CreatNode(10);
printlist(phead);
for (i=0;i<10;i++)
{
p[i] = GetOneNode(&phead);
}
printlist(phead);
for (i=9;i>=0;i--)
{
phead = ResumeOneNode(&phead, p[i]);
}
printlist(phead);
DestroyList(phead);
return 0;
}
“节点”结构中增加事务处理函数。对函数指针及回调函数还不太理解,下一步增加。
函数指针功能:建立连接,执行操作两类。