Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 4.18 Creating and Reading Symbolic Links 123


$ln -s /no/such/file myfile create a symbolic link
$ls myfile
myfile lssays it’sthere
$cat myfile so we try to look at it
cat: myfile: No such file or directory
$ls -l myfile try-loption
lrwxrwxrwx 1 sar 13 Jan 22 00:26 myfile -> /no/such/file
The filemyfiledoes exist, yetcatsays there is no such file, becausemyfileis a
symbolic link and the file pointed to by the symbolic link doesn’t exist. The-loption
tolsgives us two hints: the first character is anl,which means a symbolic link, and
the sequence->also indicates a symbolic link. Thelscommand has another option
(-F)that appends an at-sign (@) to filenames that aresymbolic links, which can help us
spot symbolic links in a directory listing without the-loption.

4.18 Creating and Reading Symbolic Links


Asymbolic link is created with either thesymlinkorsymlinkatfunction.

#include <unistd.h>
int symlink(const char *actualpath,const char *sympath);
int symlinkat(const char *actualpath,int fd,const char *sympath);
Both return: 0 if OK,−1 on error

Anew directory entry,sympath, is created that points toactualpath.It is not required
thatactualpathexist when the symbolic link is created. (Wesaw this in the example at
the end of the previous section.) Also,actualpathandsympathneed not reside in the
same file system.
Thesymlinkatfunction is similar to symlink,but thesympath argument is
evaluated relative to the directory referenced by the open file descriptor for that
directory (specified by thefdargument). If thesympathargument specifies an absolute
pathname or if thefdargument has the special valueAT_FDCWD,then symlinkat
behaves the same way assymlink.
Because theopenfunction follows a symbolic link, we need a way to open the link
itself and read the name in the link. Thereadlinkandreadlinkatfunctions do this.

#include <unistd.h>
ssize_t readlink(const char* restrictpathname,char *restrict buf,
size_t bufsize);
ssize_t readlinkat(intfd,const char* restrictpathname,
char *restrictbuf,size_tbufsize);
Both return: number of bytes read if OK,−1 on error
Free download pdf