Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 8.11Changing User IDs and Group IDs 255


#include "apue.h"

int
main(int argc, char *argv[])
{
int i;
char **ptr;
extern char **environ;

for (i = 0; i < argc; i++) /* echo all command-line args */
printf("argv[%d]: %s\n", i, argv[i]);

for (ptr = environ; *ptr != 0; ptr++) /* and all env strings */
printf("%s\n", *ptr);

exit(0);
}

Figure 8.17 Echo all command-line arguments and all environment strings

When we execute the program from Figure8.16, we get
$./a.out
argv[0]: echoall
argv[1]: myarg1
argv[2]: MY ARG2
USER=unknown
PATH=/tmp
$argv[0]: echoall
argv[1]: only 1 arg
USER=sar
LOGNAME=sar
SHELL=/bin/bash
47 morelines that aren’tshown
HOME=/home/sar
Note that the shell prompt appeared beforethe printing ofargv[0]from the second
exec.This occurred because the parent did notwaitfor this child process to finish.

8.11 Changing User IDs and Group IDs


In the UNIX System, privileges, such as being able to change the system’s notion of the
current date, and access control, such as being able to read or write a particular file, are
based on user and group IDs. When our programs need additional privileges or need
to gain access to resources that they currently aren’t allowed to access, they need to
change their user or group ID to an ID that has the appropriate privilege or access.
Similarly,when our programs need to lower their privileges or prevent access to certain
resources, they do so by changing either their user ID or group ID to an ID without the
privilege or ability access to the resource.
Free download pdf