title: Switch user at run time when program runs as root
body: <p>If some c++ program runs as root and i want to execute some of the commands with different user and read the output of that command and again switch back to root user so can someone guide me how to achieve that in linux OS &amp; c++ ?</p>
  
  <p>Below is the reference code i wrote. Can someone guide me which is correct or not ?</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  
  std::wstring PopenRead(const std::wstring &amp;cmd)
  {
      std::wstring res;
      std::string s_cmd(cmd.begin(), cmd.end());
      FILE *f = popen((const char *)s_cmd.c_str(), "r");
  
      if (f)
      {
              char buffer[1024];
              int cnt;
              int rc;
  
              while ((cnt = fread(buffer, 1, 1024, f)) &gt; 0)
              {
                      buffer[cnt] = 0;
                      std::string s_val = std::string(buffer);
                      std::wstring wsTmp(s_val.begin(), s_val.end());
                      res += wsTmp;
              }
  
              rc = pclose(f);
              std::wcout &lt;&lt; "Output is: " &lt;&lt; res &lt;&lt; std::endl;
  
              return res;
      }
      return L"";
  }
  
  int main()
  {
      std::wstring command = L"su test_user -c 'ls -ltr /home/test_user'";
      std::wstring exec_res = PopenRead(command);    
      return 0;
  }
  </code></pre>