title: correct way to run setuid programs in C
body: <p>I have a process with permissions 4750. Two users exist in my Linux system. The root user and the appz user. The process inherits the permissions of a process manager that runs as "appz" user. </p>
  
  <p>I have two basic routines:</p>
  
  <pre><code>void do_root (void)
  {
          int status;
          status = seteuid (euid);
          if (status &lt; 0) { 
          exit (status);
          }    
  }
  
  /* undo root permissions */
  void undo_root (void)
  {
  int status;
          status = seteuid (ruid);
          if (status &lt; 0) { 
                  exit (status);
          }
          status = setuid(ruid);
          if (status &lt; 0) { 
                  exit (status);
          }
  }
  </code></pre>
  
  <p>My flow is the following:</p>
  
  <pre><code>int main() {
   undo_root();
   do some stuff;
   do_root();
   bind( port 80); //needs root perm
   undo_root();
   while(1) {
  
      accept commads()
      if ( commands needs root user access)
      {
         do_root();
         execute();
         undo_root();
  
      }
  
   }
  </code></pre>
  
  <p>As you can see I want to execute some commands as root. I am trying to drop permissions temporarily and if the tasks needs root access I wrap the command between a do_root and undo_root call.</p>
  
  <p>However it seems that my program is not working. </p>
  
  <p>What is the canonical way to do it?</p>