質問

I'm providing a c++ wrapper to the thread safe strerror_r in code like this:

struct MyErrno {};
std::ostream& operator<<(std::stream& os, const MyErrno& err)
{
    const int len = 128
    char buf [len];
    os << strerror_r(errno, buf, len);
    return os;
}

This is just a simple wrapper so in C++ code I can say something like

<< MyErrno() << ..

and use the threadsafe printing of the errno. It also seems to be ok to use 128 becuase the man page says strerror_r will either return a pointer to an immutable static string (presumably null terminated) or a pointer to buf after filling it in with a null terminator regardless of size...just not sure if there's something wrong with this simple wrapper (potentially buggy)

役に立ちましたか?

解決

I don't understand the complete context in which you want to use this (in particular, what is the role of struct MyErrno, and what is StreamErrno, since your operator<< definition applies to a value of type sockaddr_in which isn't used).

However, in general terms, this is not a safe way to use errno, although it's a perfectly safe way to use strerror_r.

The problem is that you are mostly likely using this in a context like this:

if ((something) != OK) {
  std::cerr << "Something bad happened: "
            << (some value which causes your function to be called)
            << ...
}

That is, there will probably be some system call (outputting the string "Something bad happened") between the system call which failed, leaving a value in errno, and the use of errno in your function. Pretty well any system call can cause errno to be set, even if the error is harmless; consequently, best practice is to grab the value of errno immediately. This would be a good reason to use a custom type like MyError:

struct MyError {
  int error;
  MyError(int err) : error(err) {}
};

std::ostream& operator<<(std::ostream& os, const MyError& e) {
  // as with your function, but using `e.error` instead of `errno`
}

if ((something) != OK) {
  MyError e(errno);
  std::cerr << "Something bad happened: " << e
            << ...
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top