0

换句话说:
是否可以延迟某条指令,例如以某种方式延迟printf它在执行的最后执行?

4

3 回答 3

3

我写了一个用法示例atexit

#include <stdio.h>
#include <stdlib.h>

void foo(void) {
    printf("\nDone!\n");
}

int main(void) {
    atexit(foo);
    for (;;) {
        int tmp = rand() % 100; // unseeded
        printf("%02d ", tmp);
        if (!tmp) break;
    }
    return 0;
}

像往常一样,您应该检查返回值atexit()以检查错误。另请注意,以_Exit()或异常进程终止(例如:除零)终止程序不会调用atexit()call(s) 中指定的函数。

Live demo

输出可能是(不是从ideone复制的)

18 42 02 00
完毕!
于 2018-12-10T13:09:40.503 回答
1

C 语言为此提供了 atexit:

atexit - 注册一个在正常进程终止时调用的函数

于 2018-12-10T12:58:47.093 回答
1

你要int atexit (void (*func)(void));

程序正常终止func时,不带参数地自动调用所指向的函数。

例子:

#include <stdio.h>      /* puts */
#include <stdlib.h>     /* atexit */

void fnExit1(void) {
  puts("Exit function 1.");
}

void fnExit2(void) {
  puts("Exit function 2.");
}

int main(void) {
  atexit(fnExit1);
  atexit(fnExit2);
  puts("Main function.");
  return 0;
}

输出:

Main function.
Exit function 2.
Exit function 1.
于 2018-12-10T12:58:53.333 回答