C / POSIX
このプログラムは、それが呼び出された頻度のカウンターとして、自身の実行可能ファイルへのハードリンクの数を使用します。起動元のディレクトリに新しいハードリンクを作成します(その方法で同じファイルシステム上にあることが保証されているため)。そのため、書き込みアクセス許可が必要です。エラー処理を省略しました。
そのディレクトリに作成されたハードリンクの1つと同じ名前の重要なファイルがないことを確認してください。そうしないと、上書きされます。例えば実行可能ファイルが指定されている場合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最初の実行で出力するのですか?