From 6a2df4ee5e5157ac6de6fa202797fff04f2cdaf5 Mon Sep 17 00:00:00 2001 From: Michael Kerrisk Date: Sat, 30 Jun 2007 13:03:08 +0000 Subject: [PATCH] Add an example program. --- man2/chown.2 | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/man2/chown.2 b/man2/chown.2 index 70d3be350..38b0a1bc7 100644 --- a/man2/chown.2 +++ b/man2/chown.2 @@ -1,7 +1,8 @@ .\" Hey Emacs! This file is -*- nroff -*- source. .\" .\" Copyright (c) 1992 Drew Eckhardt (drew@cs.colorado.edu), March 28, 1992 -.\" Copyright (c) 1998 Andries Brouwer (aeb@cwi.nl) +.\" and Copyright (c) 1998 Andries Brouwer (aeb@cwi.nl) +.\" and Copyright (c) 2007 Michael Kerrisk .\" .\" Permission is granted to make and distribute verbatim copies of this .\" manual provided the copyright notice and this permission notice are @@ -29,6 +30,7 @@ .\" Modified 1996-11-06 by Eric S. Raymond .\" Modified 1997-05-18 by Michael Haardt .\" Modified 2004-06-23 by Michael Kerrisk +.\" 2007-07-08, mtk, added an example program; updated SYNOPSIS .\" .TH CHOWN 2 2007-07-08 "Linux" "Linux Programmer's Manual" .SH NAME @@ -187,6 +189,54 @@ as the old has got the same syscall number, and .BR chown () got the newly introduced number. +.SH EXAMPLE +.PP +The following program changes the ownership of the file named in +its second command-line argument to the value specified in its +first command-line arguemnt. +The new owner can be specified either as a numeric user ID, +or as a username (which is converted to a user ID by using +.BR getpwnam (3) +to perform a lookup in the system password file). +.nf + +#include +#include +#include +#include + +int +main(int argc, char *argv[]) +{ + uid_t uid; + struct passwd *pwd; + char *endptr; + + if (argc != 3 || argv[1][0] == '\\0') { + fprintf(stderr, "%s \\n", argv[0]); + exit(EXIT_FAILURE); + } + + uid = strtol(argv[1], &endptr, 10); /* Allow a numeric string */ + + if (*endptr != '\\0') { /* Was not pure numeric string */ + pwd = getpwnam(argv[1]); /* Try getting UID for username */ + if (pwd == NULL) { + perror("getpwnam"); + exit(EXIT_FAILURE); + } + + uid = pwd\->pw_uid; + } + + if (chown(argv[2], uid, \-1) == \-1) { + perror("chown"); + exit(EXIT_FAILURE); + } /* if */ + + exit(EXIT_SUCCESS); +} /* main */ +.fi .SH "SEE ALSO" .BR chmod (2), .BR fchownat (2),