如何在main之前或之后执行函数

在看DPDK源码时,看到了GCC attribute的constructor属性,于是就写些东东记录一下。

  • 在main函数之前执行函数:

GCC attribute扩展属性之constructor属性,使得相应函数在MAIN函数之前执行了,代码例子取自开源项目DPDK。

  • 在main函数之后执行函数

在进程退出时,如果调用了exit函数(main函数中return 一个整型与用此整型调用exit是等价的),在进程退出之前,会执行清理工作,即先调用通过atexit函数注册的清理函数,执顺序与注册顺序相反。然后为每个打开的流调用fclose,fclose会导致所有缓冲的数据都会被写到文件(比如标准输出)。

函数原型:int atexit(void (*func)(void));  //in stdlib.h

 

 

附代码:

 1 #include <stdio.h>
 2 #include <unistd.h>
 3 #include <stdlib.h>
 4 #include <string.h>
 5 #include <fcntl.h>
 6 #include <errno.h>
 7 
 8 #define PMD_REGISTER_DRIVER(d)\
 9 void devinitfn_ ##d(void);\
10 void __attribute__((constructor, used)) devinitfn_ ##d(void)\
11 {\
12         rte_eal_driver_register(&d);\
13 }
14 
15 //main函数之前执行的函数
16 void rte_eal_driver_register()
17 {
18     printf ("Enter rte_eal_driver_register...\n");
19 }
20 int drive = 0;
21 PMD_REGISTER_DRIVER(drive);
22 
23 //main函数之后执行的函数
24 void atexit_test()
25 {
26     printf("Enter atexit_test ...\n");   
27 }
28 
29 int main()
30 {
31      printf("Enter main ....\n");
32      atexit(atexit_test);
33     atexit(atexit_test);
34     printf("main: exit func will causes  all buffered output data to be flushed (written to the file)");
35      
36     //_exit(0); //如果放开此行或下一行,上一行的printf信息将不会被输出
37     //abort();   
38     return 0; //等价于调用exit(0);
39 }
40 
41    

运行结果:
Enter rte_eal_driver_register...
Enter main ....
main: exit func will causes  all buffered output data to be flushed (written to the file)Enter atexit_test ...
Enter atexit_test ...

附图(取自APUE ver2, 7.3. Process Termination ):

 

posted on 2015-12-24 00:27  marvin.li  阅读(2296)  评论(0编辑  收藏  举报

导航