【发布时间】:2014-03-30 15:28:38
【问题描述】:
我需要编写一个 shell,我的老师要求我们做一个我自己制作的用户名
char* userName = getlogin();
当我尝试编译文件时,它会在标题中显示警告,当我尝试运行程序时会出现段错误(当我使用 eclipse 运行它时,它会打印 NULL)
那么,我的问题是char* 有什么问题?为什么getlogin 给我NULL?
这是我的代码:
int main(void)
{
char input[INPUT_SIZE+1]; //user's input
char hostName[INPUT_SIZE];
//char* userName = getlogin();
char* userName = getpwuid(getuid());
if (gethostname(hostName,255)< 0) {
printf("there is no hostname\n", hostName);
exit (200);
}
int code;
code=0;
while(1)
{
printf("%d %s@%s$ ",code,userName,hostName);
fgets(input, INPUT_SIZE, stdin);
if(strcmp("\n",input) == 0)
continue;
printf("it didn't continue\n");
if(strcmp("exit\n",input)==0)
{
printf("you exit\n");
continue;
//exit(127);
}
printf("it didnt go to exit\n");
}
return EXIT_SUCCESS;
}
【问题讨论】:
-
需要看
getpwuid()的定义。你不能从 getpwuid 返回一个 char* ,除非它是堆分配的(在这种情况下你没有释放它)或者它是全局的(这是不寻常的)。很可能,你说错了。 -
另外,请确保您获得了所有需要的原型。使用没有适当原型的函数太容易出错。
-
取消注释
char* userName = getlogin();并注释掉下一行,它会起作用。
标签: c