map_uid_to_username() proposal

Tito farmatito at tiscali.it
Thu Apr 20 20:42:07 UTC 2006


On Thursday 20 April 2006 22:13, Robert P. J. Day wrote:
> 
>   what about something like this?
> 
> ===========================================================
#include <stdio.h>
#include <sys/types.h>
#include <pwd.h>
#include <stdlib.h>
 
char*
map_uid_to_username(uid_t uid)
{
	static struct passwd *pptr ;
 	struct passwd *res ;
 	char buf[100] ;
 	int ret ;
 
 	if (pptr == NULL) {
 		pptr = malloc(sizeof(struct passwd)) ;
 	}
 
 	ret = getpwuid_r(uid, pptr, buf, 100, &res) ;
 
 	if (res != NULL) {
 		return res->pw_name ;
 	} else {
+		bb_error_msg("uknown uid %d", uid); 
		return NULL ;
 	}
 }
 
 int
 main(int argc, char **argv)
 {
 	uid_t uid ;
 	char* name ;
 
 	for (uid = 0 ; uid < 20 ; uid++) {
 		if (name = map_uid_to_username(uid)) {
 			printf("%d: %s\n", uid, name) ;
 -		} else {
 -			printf("%d has no username.\n", uid) ;
 -		}
/* Move this in the function or you will waste a lot of space*/
 	}
 }
 =============================================================
> 
>   note the features of map_uid_to_username():
> 
> 1) it is obviously a single point of entry so you pay for the size
>    of that function only once.
> 
> 2) it will never allocate space for the necessary data structures
>    until it's called the first time.  (you can allocate buf the
>    same way, of course.  in fact, you probably should.)
> 
> 3) there is no possibility of a memory leak no matter how many
>    times you call it (unless the actual library routines are
>    screwed)
> 
> 4) it has just the right semantics
> 
>   thoughts?  it seems to work here.

I fear that the missing functionality even if the code is cleaner
will increase bb's size a lot.

  * if bufsize is > 0 char *name can not be set to NULL.
  *                   On success username is written on the static allocated
  *                   buffer name (and a pointer to it is returned).
  *                   On failure uid as string is written to the static <=
  *                   allocated buffer name and NULL is returned. <=
  * if bufsize is = 0 char *name can be set to NULL.
  *                   On success username is returned.
  *                   On failure NULL is returned.
  * if bufsize is < 0 char *name can be set to NULL
  *                   On success username is returned.
  *                   On failure an error message is printed and 
  *                   the program exits.  <=

Please try to actually substitute it in the code.

Ciao,
TIto

> rday
> _______________________________________________
> busybox mailing list
> busybox at busybox.net
> http://busybox.net/cgi-bin/mailman/listinfo/busybox
> 



More information about the busybox mailing list