[英]Segmentation fault (core dumped) C linux
So i have to make a program that execution results are similar to those after using command who and who am i in linux. 因此,我必须制作一个程序,其执行结果与在Linux中使用who和who is命令后的执行结果相似。 the problem is that both functions inside if(strcmp... and in else... are working when separated. 问题是如果分开,if(strcmp ...和else ...中的两个函数都可以工作。
The main issue is that i have to have them both in one file, and it just not work. 主要问题是我必须将它们都放在一个文件中,而这只是行不通。 When put together only that do something ./program am i, and ./program tells Segmentation fault (core dumped). 当仅在一起做某事时,。/程序就是我,而./程序则告诉分段错误(核心已转储)。
Second issue is that i have no clue how to make part ./program am i work properly it should return me only me: User pts/0 date time... not all of users like in else... part. 第二个问题是我不知道如何制作零件。/程序我是否可以正常工作,它应该只让我返回:用户pts / 0日期时间...并非所有用户都喜欢其他...部分。
#include <stdio.h>
#include <utmp.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <sys/types.h>
#define SHOWHOST
void show_info_who( struct utmp *utbufp )
{
if(utbufp->ut_type > 4){
time_t czas = utbufp->ut_time;
char buf[80];
struct tm* timeinfo = localtime(&czas);
printf("%-8.8s", utbufp->ut_name);
printf(" ");
printf("%-8.8s", utbufp->ut_line);
printf(" ");
strftime(buf, 80, "%F %R" , timeinfo);
printf("%s", buf);
printf(" ");
#ifdef SHOWHOST
printf("(%s)", utbufp->ut_host);
#endif
printf("\n");
}
}
int main(int argc, char *argv[])
{
struct utmp current_record;
int utmpfd;
int reclen = sizeof(current_record);
if ( (utmpfd = open(UTMP_FILE, O_RDONLY)) == -1 ){
perror( UTMP_FILE );
exit(1);
}
if(strcmp ( argv[1], "am") == 0){
if(strcmp ( argv[2], "i") == 0){
while ( read(utmpfd, ¤t_record, reclen) == reclen )
show_info_who(¤t_record);
printf("test\n");
}
close(utmpfd);
return 0;
}
while ( read(utmpfd, ¤t_record, reclen) == reclen )
show_info_who(¤t_record);
close(utmpfd);
return 0;
}
Why don't you try using, 你为什么不尝试使用
void setutent(void); // for rewinding
struct utmp *getutent(void);
Directly openning and seeking utmp file is not recommended. 不建议直接打开并查找utmp文件。 An utmp file seems to be a normal file that can freely access, but it behaves like a database. utmp文件似乎是可以自由访问的普通文件,但其行为类似于数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.