什么是回调函数
简单的说回调函数就是一个通过函数指针调用的函数。如果把函数的指针作为函数参数传递给另一个函数,当这个函数指针作为调用者而只想某个函数时,这就是回调函数。回调憾事不是由该函数实现方来直接调用,而是在特定的事件或者在特定的条件下又另外一方调用的,对已该事件或条件进行响应。
回调函数的实现机制
- 定义一个回调函数
- 提供函数实现的的程序在初始化的时候,将回调函数的函数指针注册给调用者;
- 当特定事件或者条件发生的时候,调用者使用函数指针调用回调函数对事件进行处理。
我们为什需要使用回调函数
如果对于回调函数在实际当中有什么作用感到疑惑,那么当你在读完本章节之后相信你的疑惑应该会有所消除。现在假设在我们编写的某个程序当中需要大量的使用到某些排序算法(冒泡、快速、shell等等...),
- 一个很简单的办法就是当用到排序的时候,我们就将相应的排序算法代码重新的写一次,但是这样以来代码量就很大很大了...以后会有各种的不利因素,
- 所以更近一步就是将相应的算法抽象成为某一类的排序函数,当需要使用的时候就去调用;这样以来就大大的缩短了代码量;
- 可是?还有米有一种更好的方法呢?答案是肯定的,我们可以编写一个对应的库,这个库实现了各种、各个数据类型的排序算法,但是我们应该怎么来实现这个库呢?那当然就是回调函数了!
源代码实例
现在就笔者的毕设当中的一个实例代码贴在这里:关于该程序的运行室需要的一些库,请阅读前几篇博文。
- #include
<stdio.h>
- #include
<stdlib.h>
- #include
<pcap.h>
- #include
<errno.h>
- #include
<sys/socket.h>
- #include
<netinet/in.h>
- #include
<arpa/inet.h>
- #include
<netinet/if_ether.h>
- void getpacket(u_char
*,const structpcap_pkthdr *,const u_char *);
- int
main(int argc,char **argv)
- {
-
char *dev;
-
char errbuf[PCAP_ERRBUF_SIZE];
-
pcap_t *descr;
-
dev = pcap_lookupdev(errbuf);
-
if(dev == NULL){
-
printf("%s\n",errbuf);
-
exit(1);
-
}
-
printf("DEV:%s\n",dev);
-
-
/*openthe device for sniffing*/
-
descr = pcap_open_live(dev,BUFSIZ,0,-1,errbuf);
-
if(descr == NULL){
-
printf("pcap_open_live():%s\n",errbuf);
-
exit(1);
-
}
-
pcap_loop(descr,6,getpacket,NULL);
-
-
return0;
- }
-
- void getpacket(u_char
*args,const structpcap_pkthdr *header,const u_char *packet)
- {
-
static int count = 0;
-
printf("The%d's packet has grab...\n",count);
-
count++;
- }
pcap_loop()函数注册了一个回调函数getpacket()。每当网卡设备dev有数据包到达的时候,边调用回调函数getpacket()执行相应的代码。
编译,执行结果如下:
- [#27#caopeng@caopeng-desktop
~/桌面/pcap]$gcctestpcap.c -lpcap
- [#28#caopeng@caopeng-desktop
~/桌面/pcap]$sudo ./a.out
- DEV
:eth0
- The 0's packet hasgrab...
- The 1's packet hasgrab...
- The 2's packet hasgrab...
- The 3's packet hasgrab...
- The 4's packet hasgrab...
- The 5's packet hasgrab...