gpt4 book ai didi

c - strerror_r 应该允许多大的尺寸?

转载 作者:IT老高 更新时间:2023-10-28 12:41:00 25 4
gpt4 key购买 nike

OpenGroup POSIX.1-2001 定义 strerror_r , The Linux Standard Base Core Specification 3.1 也是如此.但是我找不到对错误消息可以合理预期的最大大小的引用。我希望有一些定义可以放在我的代码中,但我找不到。

代码必须是线程安全的。这就是为什么使用 strerror_r 而不是 strerror。

有人知道我可以使用的符号吗?我应该创建自己的吗?


示例

int result = gethostname(p_buffy, size_buffy);
int errsv = errno;
if (result < 0)
{
char buf[256];
char const * str = strerror_r(errsv, buf, 256);
syslog(LOG_ERR,
"gethostname failed; errno=%d(%s), buf='%s'",
errsv,
str,
p_buffy);
return errsv;
}

来自文档:

开放组基本规范第 6 期:

ERRORS

The strerror_r() function may fail if:

  • [ERANGE] Insufficient storage was supplied via strerrbuf and buflen to contain the generated message string.

来源:

glibc-2.7/glibc-2.7/string/strerror.c:41:

    char *
strerror (errnum)
int errnum;
{
...
buf = malloc (1024);

最佳答案

对于所有情况,具有足够大的静态限制可能就足够了。如果您确实需要获取整个错误消息,可以使用 GNU version of strerror_r ,或者您可以使用标准版本并用连续更大的缓冲区轮询它,直到你得到你需要的东西。例如,你可以使用类似下面的代码。

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

/* Call strerror_r and get the full error message. Allocate memory for the
* entire string with malloc. Return string. Caller must free string.
* If malloc fails, return NULL.
*/
char *all_strerror(int n)
{
char *s;
size_t size;

size = 1024;
s = malloc(size);
if (s == NULL)
return NULL;

while (strerror_r(n, s, size) == -1 && errno == ERANGE) {
size *= 2;
s = realloc(s, size);
if (s == NULL)
return NULL;
}

return s;
}

int main(int argc, char **argv)
{
for (int i = 1; i < argc; ++i) {
int n = atoi(argv[i]);
char *s = all_strerror(n);
printf("[%d]: %s\n", n, s);
free(s);
}

return 0;
}

关于c - strerror_r 应该允许多大的尺寸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/423248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com