So i have to make a program that execution results are similar to those after using command who and who am i in linux. the problem is that both functions inside if(strcmp… and in else… are working when separated.
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.
#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("testn");
}
close(utmpfd);
return 0;
}
while ( read(utmpfd, ¤t_record, reclen) == reclen )
show_info_who(¤t_record);
close(utmpfd);
return 0;
}
Advertisement
Answer
Why don’t you try using,
void setutent(void); // for rewinding
struct utmp *getutent(void);
Directly openning and seeking utmp file is not recommended. An utmp file seems to be a normal file that can freely access, but it behaves like a database.