The Linux Programming Interface

(nextflipdebug5) #1
File Attributes 293

When changing the owner or group of a file, the set-group-ID permission bit is not
turned off if the group-execute permission bit is already off or if we are changing
the ownership of a directory. In both of these cases, the set-group-ID bit is being
used for a purpose other than the creation of a set-group-ID program, and there-
fore it is undesirable to turn the bit off. These other uses of the set-group-ID bit are
as follows:


z If the group-execute permission bit is off, then the set-group-ID permission bit
is being used to enable mandatory file locking (discussed in Section 55.4).


z In the case of a directory, the set-group-ID bit is being used to control the own-
ership of new files created in the directory (Section 15.3.1).


The use of chown() is demonstrated in Listing 15-2, a program that allows the user to
change the owner and group of an arbitrary number of files, specified as command-
line arguments. (This program uses the userIdFromName() and groupIdFromName()
functions from Listing 8-1, on page 159, to convert user and group names into cor-
responding numeric IDs.)


Listing 15-2: Changing the owner and group of a file


–––––––––––––––––––––––––––––––––––––––––––––––––––––––––– files/t_chown.c
#include <pwd.h>
#include <grp.h>
#include "ugid_functions.h" / Declarations of userIdFromName()
and groupIdFromName()
/
#include "tlpi_hdr.h"


int
main(int argc, char *argv[])
{
uid_t uid;
gid_t gid;
int j;
Boolean errFnd;


if (argc < 3 || strcmp(argv[1], "--help") == 0)
usageErr("%s owner group [file...]\n"
" owner or group can be '-', "
"meaning leave unchanged\n", argv[0]);


if (strcmp(argv[1], "-") == 0) { / "-" ==> don't change owner /
uid = -1;
} else { / Turn user name into UID /
uid = userIdFromName(argv[1]);
if (uid == -1)
fatal("No such user (%s)", argv[1]);
}


if (strcmp(argv[2], "-") == 0) { / "-" ==> don't change group /
gid = -1;

Free download pdf