Linux 应用程序开发之设置用户和组

#include 
#include 
#include 
#include 

...

gchar *user = NULL;
gchar *group = NULL;

...

if(group)
{
    struct group *grp = NULL;

    if(NULL == (grp = getgrnam(group)))
      g_error("%s:%d[%s]=>(%s)", __FILE__, __LINE__,
                  __FUNCTION__, "Get group failed!");

    if(-1 == setgid(grp->gr_gid))
      g_error("%s:%d[%s]=>(%s)", __FILE__, __LINE__,
                  __FUNCTION__, "Set gid failed!");
    if(-1 == setgroups(0, NULL))
      g_error("%s:%d[%s]=>(%s)", __FILE__, __LINE__,
                  __FUNCTION__, "Set groups failed!");
    if(user)
    {
        if(-1 == initgroups(user, grp->gr_gid))
          g_error("%s:%d[%s]=>(%s)", __FILE__, __LINE__,
                      __FUNCTION__, "Init groups failed!");
    }
}

if(user)
{
    struct passwd *pwd = NULL;

    if(NULL == (pwd = getpwnam(user)))
      g_error("%s:%d[%s]=>(%s)", __FILE__, __LINE__,
                  __FUNCTION__, "Get user failed!");

    if(-1 == setuid(pwd->pw_uid))
      g_error("%s:%d[%s]=>(%s)", __FILE__, __LINE__,
                  __FUNCTION__, "Set uid failed!");
}

...

Over!

Leave a Reply

Your email address will not be published.