prosource

리눅스에서 C/C++로 사용자 이름을 얻는 방법은 무엇입니까?

probook 2023. 7. 17. 21:14
반응형

리눅스에서 C/C++로 사용자 이름을 얻는 방법은 무엇입니까?

환경을 사용하지 않고 어떻게 실제 "사용자 이름"을 얻을 수 있습니까?getenv...) 프로그램에서?환경은 Linux를 사용하는 C/C++입니다.

에서 정의된 함수unistd.h사용자 이름을 반환합니다.man getlogin_r자세한 정보는.

서명은 다음과 같습니다.

int getlogin_r(char *buf, size_t bufsize);

말할 필요도 없이, 이 함수는 C나 C++에서도 쉽게 호출될 수 있습니다.

http://www.unix.com/programming/21041-getting-username-c-program-unix.html 에서:

/* whoami.c */
#define _PROGRAM_NAME "whoami"
#include <stdlib.h>
#include <pwd.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
  register struct passwd *pw;
  register uid_t uid;
  int c;

  uid = geteuid ();
  pw = getpwuid (uid);
  if (pw)
    {
      puts (pw->pw_name);
      exit (EXIT_SUCCESS);
    }
  fprintf (stderr,"%s: cannot find username for UID %u\n",
       _PROGRAM_NAME, (unsigned) uid);
  exit (EXIT_FAILURE);

}

메인 라인을 사용하여 클래스에서 캡슐화하면 됩니다.

class Env{
    public:
    static std::string getUserName()
    {
        uid_t uid = geteuid ();
        struct passwd *pw = getpwuid (uid);
        if (pw)
        {
            return std::string(pw->pw_name);
        }
        return {};
    }
};

C의 경우에만:

const char *getUserName()
{
  uid_t uid = geteuid();
  struct passwd *pw = getpwuid(uid);
  if (pw)
  {
    return pw->pw_name;
  }

  return "";
}
#include <iostream>
#include <unistd.h>
int main()
{
    std::string Username = getlogin();
    std::cout << Username << std::endl;
    return 0 ;
}

또 다른 방법은...

#include <iostream>
using namespace std;
int main()
{
       cout << system("whoami");
}

사용하다char *cuserid(char *s)에서 발견된.stdio.h.

#include <stdio.h>

#define MAX_USERID_LENGTH 32

int main()
{
  char username[MAX_USERID_LENGTH];
  cuserid(username);
  printf("%s\n", username);
  return 0;
}

자세한 내용은 다음을 참조하십시오.

  1. https://pubs.opengroup.org/onlinepubs/007908799/xsh/cuserid.html
  2. https://serverfault.com/questions/294121/what-is-the-maximum-username-length-on-current-gnu-linux-systems

현대적인 C++ 사양을 조금 살펴봅니다.

static auto whoAmI = [](){ struct passwd *tmp = getpwuid (geteuid ());
  return tmp ? tmp->pw_name : "onlyGodKnows"; 
}

오늘도 같은 작업을 해야 했지만, OS별 헤더를 포함하고 싶지 않았습니다.Linux/Windows 전용 헤더에 의존하지 않고 크로스 플랫폼 방식으로 수행할 수 있는 작업은 다음과 같습니다.

#include <stdio.h> 
#include <memory>
#include <stdexcept>
#include <array>
#include <regex>

std::string execute_command(std::string cmd) 
{
    std::array<char, 128> buffer;
    std::string result;
    
    #if defined(_WIN32)
        #define POPEN _popen
        #define PCLOSE _pclose
    #elif defined(unix) || defined(__unix__) || defined(__unix)
        #define POPEN popen
        #define PCLOSE pclose
    #endif

    std::unique_ptr<FILE, decltype(&PCLOSE)> pipe(POPEN(cmd.c_str(), "r"), PCLOSE);
    if (!pipe) 
    {
        throw std::runtime_error("popen() failed!");
    }
    while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) 
    {
        result += buffer.data();
    }
    return result;
}
std::string get_current_username()
{
    #if defined(_WIN32)
        // whoami works on windows as well but it returns the name 
        // in the format of `computer_name\user_name` so instead
        // we use %USERNAME% which gives us the exact username.
        #define USERNAME_QUERY "echo %USERNAME%" 
    #elif defined(unix) || defined(__unix__) || defined(__unix)
        #define USERNAME_QUERY "whoami"
    #endif
    auto username = execute_command(USERNAME_QUERY);
    // this line removes the white spaces (such as newline, etc)
    // from the username.
    username = std::regex_replace(username, std::regex("\\s"), "");
    return username;
    
}

이것은 Linux와 Windows 모두에서 잘 작동하며 C++11과 호환됩니다!

온라인 테스트: https://paiza.io/projects/e/xmBuf3rD7MhYca02v5V2dw?theme=twilight

언급URL : https://stackoverflow.com/questions/8953424/how-to-get-the-username-in-c-c-in-linux

반응형