我应该允许多大的strerror_r? [英] What size should I allow for strerror_r?

查看:117
本文介绍了我应该允许多大的strerror_r?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

OpenGroup POSIX.1-2001定义 strerror_r Linux标准基础内核规范3.1 .但是我找不到对错误消息可以合理预期的最大大小的引用.我希望可以在代码中定义一些地方,但是找不到.

The OpenGroup POSIX.1-2001 defines strerror_r, as does The Linux Standard Base Core Specification 3.1. But I can find no reference to the maximum size that could be reasonably expected for an error message. I expected some define somewhere that I could put in my code but there is none that I can find.

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

The code must be thread safe. Which is why strerror_r is used and not strerror.

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

Does any one know the symbol I can use? I should I create my own?

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期:

The Open Group Base Specifications Issue 6:

错误

在以下情况下,strerror_r()函数可能会失败:

The strerror_r() function may fail if:

  • [ERANGE] ,通过strerrbuf和buflen提供的存储空间不足 包含生成的消息字符串.
  • [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:

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

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

推荐答案

具有足够大的静态限制可能足以满足所有情况. 如果您确实需要获取整个错误消息,则可以使用 GNU版本的strerror_r ,也可以使用标准版本 并使用依次更大的缓冲区对其进行轮询,直到获得所需的内容为止.例如, 您可以使用类似下面的代码.

Having a sufficiently large static limit is probably good enough for all situations. If you really need to get the entire error message, you can use the GNU version of strerror_r, or you can use the standard version and poll it with successively larger buffers until you get what you need. For example, you may use something like the code below.

#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;
}

这篇关于我应该允许多大的strerror_r?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆