System Calls
This is chapter 3, you should read it.
As we discussed previously, the linux API is through system calls.
Some of these are wrapped by glibc to give us library functions that are easier to use.
The difference between the two really doesn't matter to me.
Let's write some code.
A simple program that allows the user to move around the file system.
Perhaps the basics of a shell
The program prints the current directory.
Then reads in the user's response.
on
QUIT
the program exits.
Otherwise it attempts to change to the directory given.
Print errors when a problem occurs.
Start by looking at the man page for
chdir
Notice the include file listed.
Notice that there are two different forms
One that takes a
const char *
This is either a relative or absolute path
But not a ~ path, the shell does this.
The second takes an
int
This is for a file descriptor, not a path
Read the descriptions, make sure you understand what they do.
Notice the return value
0 on success, -1 on fail
This is very common, but not universal
Pay attention to this.
errno
man errno
This is set by the kernel if an error occurs
It is
NEVER
unset.
Library calls such as cout, could change this as ell.
Best to do the following
if (test for fail on system call) { do something with errno }
Back to this in a bit.
Back to chdir, look at the errors
Some of these make sense (EACCESS)
Some of them are scary (ENOMEM)
Some will make sense later (ELOOP)
Last thing to look at here is
See Also
getcwd
looks like it might be a system call we want.
path_resolution
is probably some theory, man 7 usually is.
chroot
is more advanced.
errors
What do you do when you have an error?
The errno might give you a way to recover
Or at least print an error message and exit.
chdir is nice in that it will not change anything on error. No recovery.
But it is nice to know what the problem is.
There are several library functions which help
perror (char *)
Takes a user supplied message
And prints the message and the error string.
Needs <stdio.h> for c
but I also got away with <string.h>
strerror
Will return the error string given the error number.
<cstring> and <cerrno> for c++
Use this string immediately or copy it.
It will be overwritten.
Do not free this string.
read the man page for
getcwd
Make
I use make.
You should too.
You should ask questions about it now, or any time in the future.