whoami.c源代码

2013-02-06

实现一个linux的命令:whoami,首先用getuid()获取uid,然后根据uid和struct passwd获取用户信息。

getuid()所需头文件:
#include <sys/types.h>
#include <unistd.h>

uid_t  getuid(void);

struct passwd所需头文件:

#include <pwd.h>

struct passwd
{
char * pw_name; /* Username, POSIX.1 */
char * pw_passwd; /* Password */
__uid_t pw_uid; /* User ID, POSIX.1 */
__gid_t pw_gid; /* Group ID, POSIX.1 */
char * pw_gecos; /* Real Name or Comment field */
char * pw_dir; /* Home directory, POSIX.1 */
char * pw_shell; /* Shell Program, POSIX.1 */
};

whoami.c源代码:
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <pwd.h>

int main (int argc, char **argv)
{
uid_t my_uid;
struct passwd *my_info;

my_uid = getuid ();
my_info = getpwuid (my_uid);

if (my_info)
{
printf ("My Login Name:%s\n", my_info->pw_name);
printf ("My User ID :%ld\n", my_info->pw_uid);
printf ("My Real Name:%s\n", my_info->pw_gecos);
printf ("My Home Dir :%s\n", my_info->pw_dir);
printf ("My Work Shell:%s\n", my_info->pw_shell);
}
}

编译:

gcc whoami.c -o whoami

分类:Linux操作系统编程 | 标签: |

相关日志

评论被关闭!