write:用于终端之间的用户通信。
write [username] [终端]
代码实现
#include
#include
#include
#include
#include
#include
#include
#include
#define PATH "/var/run/utmp"
#define PREPATH "/dev/"
char BUF[4096];
char *getpath(char *);
void write_p(char *);
int main(int ac,char **av)
{
if(ac != 2&&ac != 3){
return ;
}
char *str;
if(ac == 2){
str = getpath(av[1]);
write_p(str);
return ;
}
if(find(av[2],av[1])) {
printf("%s is not login this \n",av[1]);
return;
}
write_p(av[2]);
}
char *getpath(char *name)//return stt* pts/*
{
if(name == NULL) return NULL;
struct utmp p;
char *str = (char *)malloc(sizeof(char)*UT_LINESIZE);
int fp;
ssize_t rd;
if((fp = open(PATH,O_RDONLY)) == -1){
perror(PATH);
exit(-1);
}
while((rd = read(fp,&p,sizeof(struct utmp))) != 0)
{
if(rd == -1){
perror(PATH);
exit(-1);
}
if(strcmp(name,p.ut_user) == 0) strcpy(str,p.ut_line);
}
if(strlen(str) == 0) {
printf("no login\n");
exit(-1);
}
return str;
}
void write_p(char *path)
{
int fp;
ssize_t rd;
char str[256];
strcpy(str,PREPATH);
strcat(str,path);
if((fp = open(str,O_WRONLY)) == -1){
perror(str);
exit(-1);
}
while(fgets(BUF,4096,stdin) != NULL)
{
if(write(fp,BUF,strlen(BUF)) == -1){
perror(str);
exit(-1);
}
}
return ;
}
int find(char *path,char *name)
{
int fp;
ssize_t rd;
struct utmp x;
if((fp = open(PATH,O_RDONLY)) == -1){
perror(PATH);
exit(-1);
}
while((rd = read(fp,&x,sizeof(struct utmp))) != 0){
if(rd == -1){
perror(PATH);
exit(-1);
}
if(strcmp(path,x.ut_line) == 0 && strcmp(name,x.ut_user) == 0) return 0;
}
return 1;
}