This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
/* Equivalent to `id -un'. */ /* Written by Richard Mlynarik. */ //注意包含的头文件里多了个pwd.h #include #include #include #include #include //包含进来本地的4个头文件 #include "system.h" #include "error.h" #include "long-options.h" #include "quote.h"
/* The official name of this program (e.g., no `g' prefix). */ #define PROGRAM_NAME "whoami" //定义宏PROGRAM_NAME,其值为一个字符串
/* The name this program was run with. */ char *program_name; //声明全局字符指针变量
void usage (int status)//帮助函数 { if (status != EXIT_SUCCESS)//如果传入的形参不等于EXIT_SUCCESS,则: fprintf (stderr, _("Try `%s --help' for more information.\n"), program_name);//向标准错误打印一串字符串 else//否则,如果status等于EXIT_SUCCESS,则打印下面的字符串文本 { printf (_("Usage: %s [OPTION]...\n"), program_name); fputs (_("\ Print the user name associated with the current effective user ID.\n\ Same as id -un.\n\ \n\ "), stdout);//这个打印的字符串简单地说明了这个程序的用途,打印当前用户的eid,有效用户id fputs (HELP_OPTION_DESCRIPTION, stdout); fputs (VERSION_OPTION_DESCRIPTION, stdout); printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT); } exit (status);//函数退出的状态值是传入的形参的值 }
int main (int argc, char **argv)//标准的main函数定义 { struct passwd *pw; /* struct passwd 这个结构体是在头文件pwd.h里面定义的,详细如下: struct passwd { char *pw_name; //用户名
uid = geteuid ();//uid变量在这里得到值,是通过系统调用geteuid()得到的,其定义为: // uid_t geteuid(void); 这个系统调用据说永远不会失败 pw = getpwuid (uid); /* getpwuid库函数的man解释如下: The getpwuid() function returns a pointer to a structure containing the broken out fields of a line from /etc/passwd for the entry that matches the user uid uid. 改库函数一个指向/etc/passwd文件的响应uid的行
*/ if (pw)//pw是getpwuid()库函数的返回,这个指针返回是空指针的情况为: //NULL if the matching entry is not found or an error occurs 就是传入的uid不存在的情况 {//如果得到的指针pw不是空指针,则输出此结构体里的用户名 puts (pw->pw_name); exit (EXIT_SUCCESS);//此时main函数正常返回 } fprintf (stderr, _("%s: cannot find name for user ID %lu\n"), program_name, (unsigned long int) uid);//如果执行流程走到这里,就说明没有正常获取到pw,此时打印错误 exit (EXIT_FAILURE);//这时候退出状态肯定不是成功了,而是失败 }