C / POSIX
该程序使用到其可执行文件的硬链接数作为其调用频率的计数器。它将在其起始目录中创建新的硬链接(因为这样可以确保它位于同一文件系统上),因此需要写许可权。我已经省略了错误处理。
最好确保没有与该目录上创建的硬链接之一同名的重要文件,否则它将被覆盖。如果例如可执行文件被命名counter
,则硬链接将被命名counter_1
,counter_2
等等。
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
/* get persistent counter */
struct stat selfstat;
stat(argv[0], &selfstat);
int counter = selfstat.st_nlink;
/* determine digits of counter */
int countercopy = counter;
int digits = 1;
while (countercopy /= 10)
++digits;
/* increment persistent counter */
char* newname = malloc(strlen(argv[0]) + digits + 2);
sprintf(newname, "%s_%d", argv[0], counter);
link(argv[0], newname);
/* output the counter */
if (counter & (counter-1)) // this is zero iff counter is a power of two
printf("%d\n", counter);
else
{
/* determine which power of 2 it is */
int power = 0;
while (counter/=2)
++power;
printf("2^%d\n", power);
}
return 0;
}
运行示例(如果可执行文件已经运行,第一行将重置计数器):
$ rm counter_*
$ ./counter
2^0
$ ./counter
2^1
$ ./counter
3
$ ./counter
2^2
$ ./counter
5
$ ./counter
6
$ ./counter
7
$ ./counter
2^3
$ ./counter
9
$ ls counter*
counter counter_2 counter_4 counter_6 counter_8 counter.c
counter_1 counter_3 counter_5 counter_7 counter_9 counter.c~
0
在第一次运行中输出?