On Wed, Jan 10, 2007 at 01:22:45PM -0500, as wrote:
> [sorry for duplicate posting]
> 
> Hi,
> 
> I'm trying to use sched_setscheduler() to increase the priority of a
> process but I get this error
> 
> sched_setscheduler() failed: Operation not permitted
> 
> I understand that the process that is calling this function needs to be
> privileged, but I don't want to run this as root. How do I elevate the
> privilege of the process or the user calling this process?
> 
> I'm using Debian.

The "correct" way to do this is for the process you're running to be setuid 
root,
to call sched_setscheduler(), then use setuid(getuid()) to drop priviledges.

There is probably a better way to find the right user to setuid() back to, but 
this
is the code I use (that handles the seperate case of when I invoke this as a 
`sudo -s`
root user):

void drop_priviledges()
{
        uid_t uid;
        gid_t gid;
        char * user;
        struct passwd * pw;
        int err;

        uid=getuid();
        gid=getgid();
        if((uid == 0)||(gid==0))        // we are probably in a sudo_shell
        {
                user = getenv("USER");
                if((!user)||(!strcmp(user,"root")))
                {
                        user = getenv("SUDO_USER");
                }
                if(!user)
                {
                        sidecarlog(LOGCRIT,"failed to drop priviledges\n");
                        return;
                }
                pw = getpwnam(user);
                if(!pw)
                {
                        sidecarlog(LOGCRIT,"failed to drop priviledges: 
getpwnam()\n");
                        return;
                }
                uid=pw->pw_uid;
                gid=pw->pw_gid;
                if(uid == 0)
                {
                        sidecarlog(LOGCRIT,"failed to drop priviledges: uid 
still 0()\n");
                        return;
                }
        }
        setgid(gid);            // who cares if setgid fails
        err = setuid(uid);
        if(err)
        {
                sidecarlog(LOGCRIT,"failed to drop priviledges: setuid(): 
%s\n",strerror(errno));
        }
        else
        {
                sidecarlog(LOGINFO,"dropped priviledges to uid %d gid 
%d\n",uid,gid);
        }
}

Reply via email to