- Let's take a look at two system calls.
- int gethostname(char *name, size_t len);
- int sethostname(const char *name, size_t len);
- The first will attempt to get the system's host name.
- The second will attempt to set the system's host name.
- These routines require the user to supply a memory location
- Take a quick look at the man pages.
- Note the description
- Note the return value
- Note errors
- So an acceptable program might be
// myHostName.C
#include <iostream>
#include <unistd.h> // get/set hostname
#include <limits.h> // for HOST_NAME_MAX
using namespace std;
const int LEN = HOST_NAME_MAX;
int main() {
char name[LEN];
gethostname(name, LEN);
cout << "The host name is " << name << endl;
return 0;
}
- And this probably would be safe for a normal program but.
- But we are writing systems utilities, and we want to be a little more careful.
- Note that system calls can set errno and the documentation on how this is set
// errors.C
int main() {
char name[LEN];
char eName[1];
cout << "Before the call errno is " << errno << endl;
gethostname(eName, 1);
cout << "After the first call errno is " << errno << endl;
sethostname(eName, 1);
cout << "After the second call errno is " << errno << endl;
return 0;
}
- Notice several things
-
- errno may be set, but it may also be changed by additional system calls.
- the number alone in meaningless.
- But note, it does not automatically get set to 0 after an error.
- So you need to use errno right away if there is an error
- And not really trust errno to tell you that there was an error.
- void perror(const char *s);
- A second alternative is strerror
- Needs string.h
- char *strerror(int errnum);
- The pointer returned is to system memory, not yours
- You should not modify or free it.
- It will be changed by other calls to strerror
- strerror may cause an error, thus errno may be changed.
// part of error3.C
int errorNum;
char * errorMessage;
if (0 != gethostname(eName, 1)) {
errorNum = errno;
errorMessage = strerror(errorNum);
cerr << "\tThe call to gethostname failed" << endl ;
cerr << "\tThe system says " << errorMessage << endl;
}