linux getpwuid 得到指定使用者資訊

來源:互聯網
上載者:User
和系統資料相關的passwd 結構

和系統資料相關的一個結構passwd定義如下

/* The passwd structure.      */
struct passwd
{
      char *pw_name;       /* 使用者名稱*/
      char *pw_passwd;     /* 密碼.*/
      __uid_t pw_uid;      /* 使用者ID.*/
      __gid_t pw_gid;      /*組ID.*/
      char *pw_gecos;      /*真實名*/
      char *pw_dir;        /* 主目錄.*/
      char *pw_shell;      /*使用的shell*/
};

該結構描述了/etc/passwd的檔案記錄行 包括使用者名稱 密碼 使用者ID 使用者組ID 真實姓名 使用者主目錄和默預設SHELL
相關的API有
struct passwd *getpwuid(uid uid)
struct paswd *getpwnam(const char *name)

getpwuid 根據傳入的使用者ID返回指向passwd的結構體 該結構體初始化了裡面的所有成員
getpwnam 和getpwuid一樣 只是傳入的參數是使用者名稱

小試牛刀:這個程式只是作示範並沒有作錯誤處理

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <pwd.h>
int main (void)
{
       struct passwd *passwd;
       passwd=getpwuid(getuid());
       /** passwd=getcwnam("phpos"); **/
       printf("Username:%s/n",passwd->pw_name);
       printf("Password:%s/n",passwd->pw_passwd);
       printf("uid:%d/n",passwd->pw_uid);
       printf("gid:%d/n",passwd->pw_gid);
       printf("shell:%s/n",passwd->pw_shell);
       printf("dir:%s/n",passwd->pw_dir);
       return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.