簡體   English   中英

在UNIX類型的操作系統中獲取當前用戶帳戶的顯示名稱

[英]Getting the current user account's display name in UNIX-type operating systems

在Windows中,用戶帳戶具有帳戶名和與該帳戶相關聯的“真實名稱”。 可以通過GetUserNameEx()進行檢索。

同樣,在UNIX類型的操作系統中,存在“手指信息”(由chfn等設置,以及通過桌面UNIXen上的各種GUI工具設置)。 在UNIX類型的OS(例如macOS和Linux)中,用戶進程如何檢索這些信息?

理想的解決方案將使用libc API,而不必依賴於僅生成finger進程等。

在類似Unix的系統上,我可能會先調用getuid ,然后再getuid getpwuidgetpwuid_r

就像是:

#include <pwd.h>
#include <stdio.h>
#include <unistd.h>

int
main(void)
{
    struct passwd *pw;

    pw = getpwuid(getuid());

    if (pw == 0) {
        perror("getpwuid failed");
        return 1;
    }

    printf("username: %s; realname: '%s'\n", pw->pw_name, pw->pw_gecos);

    return 0;
}

Shell腳本解決方案:

在Linux上,可以在子getent passwd中使用getent passwd ,然后解析出實名字段(應該是逗號之間的第五個字段)。

在macOS上,您可以使用id -f

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM