当前位置: C语言 -- 附录 -- set_constraint_handler_s

set_constraint_handler_s函数


概要:
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdlib.h>
constraint_handler_t set_constraint_handler_s(
      constraint_handler_t handler);

描述:

该函数将参数handler设置为运行约束处理程序。当库函数检测到运行约束冲突时,将调用通过set_constraint_handler_s函数最近注册的运行约束处理程序。参数handler应为constraint_handler_t类型,该类型定义如下所示:

typedef void (*constraint_handler_t)(
     const char * restrict msg, 
     void * restrict ptr, 
     errno_t error);

其中:

msg -- 指向描述运行约束冲突字符串的指针。

ptr -- 空指针或者指向实现定义对象的指针。

error -- 如果调用运行约束处理程序的安全函数的返回类型是errno_t,参数error是安全函数的返回值;否则参数error为传递的errno_t类型的正值。


如果实现没有通过set_constraint_handler_s函数设置运行约束处理程序,实现将使用默认运行约束处理程序,默认运行约束处理程序的行为由实现定义,它可能导致程序正常终止(exit)或者异常终止(abort)。

如果参数handler为空指针,实现默认的运行约束处理程序即为当前运行约束处理程序。


参数:
constraint_handler_t handler

空指针或者constraint_handler_t类型的对象。


返回值:

函数返回指向先前注册的运行约束处理程序的指针。如果前一个处理程序是通过调用set_constraint_handler_s(NULL)注册的,函数返回指向实现默认处理程序的指针,而不是空指针。


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
/*安全函数set_constraint_handler_s范例*/

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <stdlib.h>

void runtimeConstraintHandler(const char *msg, void *ptr, errno_t error)
{
    printf_s("Runtime constraint violation: %s\n", msg);
    printf_s("Error code: %d\n", error);
}

int main(void)
{
    set_constraint_handler_s(runtimeConstraintHandler);

    FILE *pFile;
    char *mode = NULL;
    fopen_s(&pFile, "gch.txt", mode);  //运行约束:mode不能为空指针。
    fclose(pFile);

    return 0;
}


结果:

注:测试时Visual Studio软件还未支持set_constraint_handler_s函数,以上例子仅供参考。


相关内容:
abort_handler_s 发生运行约束冲突时终止调用安全函数的安全函数。
ignore_handler_s 发生运行约束冲突时忽略运行约束冲突的安全函数。