Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 4.24 Device Special Files 137


#include "apue.h"
int
main(void)
{
char *ptr;
size_t size;
if (chdir("/usr/spool/uucppublic") < 0)
err_sys("chdir failed");
ptr = path_alloc(&size); /* our own function */
if (getcwd(ptr, size) == NULL)
err_sys("getcwd failed");
printf("cwd = %s\n", ptr);
exit(0);
}

Figure 4.24Example ofgetcwdfunction

Note thatchdirfollows the symbolic link—as we expect it to, from Figure4.17 — but
when it goes up the directory tree,getcwdhas no idea when it hits the/var/spool
directory that it is pointed to by the symbolic link/usr/spool.This is a characteristic
of symbolic links.

Thegetcwdfunction is useful when we have an application that needs to return to
the location in the file system where it started out.We can save the starting location by
callinggetcwd before we change our working directory.After we complete our
processing, we can pass the pathname obtained fromgetcwdtochdirto return to our
starting location in the file system.
Thefchdirfunction provides us with an easy way to accomplish this task. Instead
of callinggetcwd, we canopenthe current directory and save the file descriptor before
we change to a different location in the file system. When we want to return to where
we started, we can simply pass the file descriptor tofchdir.

4.24 Device Special Files


The two fieldsst_devandst_rdevareoften confused.We’ll need to use these fields
in Section 18.9 when we write thettynamefunction. Therules for their use aresimple.

•Every file system is known by its major and minor device numbers, which are
encoded in the primitive system data typedev_t.The major number identifies
the device driver and sometimes encodes which peripheral boardto
communicate with; the minor number identifies the specific subdevice. Recall
from Figure4.13 that a disk drive often contains several file systems. Each file
system on the same disk drive would usually have the same major number,but
adifferent minor number.
Free download pdf