COHERENT manpages
This page displays the COHERENT manpage for link() [Create a link].
List of available manpages
Index
link() -- System Call (libc)
Create a link
#include <unistd.h>
link(old, new)
char *old, *new;
A link to a file is another name for the file. All attributes of the file
appear identical among all links.
link() creates a link called new to an existing file named old.
For administrative reasons, it is an error for users other than the
superuser to create a link to a directory. Such links can make the file
system no longer tree structured unless carefully controlled, posing
problems for commands such as find.
Examples
The first example, called lock.c, demonstrates how link() can be used to
perform intertask locking. With this technique, a program can start a
process in the background and stop any other user from starting the
identical process.
#include <unistd.h>
main()
{
if(link("lock.c", "lockfile") == -1) {
printf("Cannot link\n");
exit(1);
}
sleep(50); /* do nothing for 50 seconds */
unlink("lockfile");
printf("done\n");
exit(EXIT_SUCCESS);
}
The second example demonstrates how to use link() and unlink() to rename a
file.
#include <stdio.h>
#include <unistd.h>
main(argc, argv) int argc; char *argv[];
{
register char *old, *new;
if (argc != 3) {
fprintf(stderr, "Usage: rename old new\n");
exit(EXIT_FAILURE);
}
old = argv[1];
new = argv[2];
if (link(old, new) == -1) {
fprintf(stderr, "rename: link(%s, %s) failed\n", old, new);
exit(EXIT_FAILURE);
} else if (unlink(old) == -1) {
fprintf(stderr, "rename: unlink(%s) failed\n", old);
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
See Also
find,
libc,
ln,
rename(),
unlink(),
unistd.h
POSIX Standard, §5.3.4
Diagnostics
link() returns zero when successful. It returns -1 on errors, e.g., old
does not exist, new already exists, attempt to link across file systems, or
no permission to create new in the target directory.
Notes
Because each mounted file system is a self-contained entity, links between
different mounted file systems fail.