The Linux Write command allows users to talk to users on other terminals. Implement the shell command write in C, with the following code:
#include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <utmp.h> #include <pwd.h > #include <sys/types.h> #include <stdlib.h> #include <sys/stat.h> #include <time.h>char * Get_terminal_name (char *); char * get_terminal_name_by_user_name (char *); void hello (); int main (int argc, char * argv[]) {i NT Fd;char Buffer[1024];char * TERMINAL_NAME;IF (argc! = 2) {printf ("Write Usage:write [Ttyname|username]"); return 1;} Terminal_name = Get_terminal_name (argv[1]), if (terminal_name = = NULL) {printf ("Get Terminal name error\n"); return 1;} printf ("terminate_name:%s", terminal_name); fd = open (terminal_name,o_wronly); hello (fd); while (Fgets (buffer,1024, stdin)! = EOF) {Write (Fd,buffer,strlen (buffer));} Close (FD); return 0;} void Hello (int fd) {char greeting[1024];struct passwd * passwd_pointer;time_t Now;char host[255];gethostname (host, 255); Time (&now);p asswd_pointer = Getpwuid (Getuid ()); sprintf (Greeting, "Message from%[email protected]%s to%s at%") 5.5s... \ n ", Passwd_pointer->pw_name, Host, Ttyname (0), CTime (&now) + one); Write (Fd,greeting,strlen (greeting));} char * get_terminal_name (char * user_input) {char terminal_name[255];struct stat stat_buffer;if (Lstat, & Stat_buffer)! =-1) {if (S_ISCHR (Stat_buffer.st_mode)) {return user_input;}} Return Get_terminal_name_by_user_name (user_input);} char * get_terminal_name_by_user_name (char * user_name) {struct utmp * utmp_pointer;setutent (); int number = 0;char * Resul t = (char *) malloc (sizeof (char) * 255); char *mytty = ttyname (0); /* begins "/dev/" */char *ttydev = Mytty + strlen ("/dev/");p rintf ("%s\n", Mytty), while ((Utmp_pointer = Getutent ())! = NUL L) {if (strcmp (user_name, utmp_pointer->ut_user) = = 0&& Utmp_pointer->ut_type = user_process&& strcmp (Utmp_pointer->ut_line, ttydev)! = 0&& Utmp_pointer->ut_line[0]! = ': ') {number++;//printf ("%s\n" , Utmp_pointer->ut_line), if (number = = 1) {strcpy (result, "/dev/"); strcat (result, utmp_pointer->ut_line);}}} Endutent (); if (number > 1) printf ("warning:%s is logged in%d different terminals,using%s\n", user_name, number, result) if (number = = 0) return null;return result;
Write the shell command yourself