自己動手寫shell命令之write

來源:互聯網
上載者:User

標籤:unix環境進階編程   shell   linux   

Linux下write命令允許使用者跟其他終端上的使用者對話。用c語言實現shell命令write,代碼如下:

#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[]) {int 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);passwd_pointer = getpwuid(getuid());sprintf(greeting, "Message from %[email protected]%s on %s at %5.5s ...\n",passwd_pointer->pw_name, host, ttyname(0), ctime(&now) + 11);write(fd,greeting,strlen(greeting));}char * get_terminal_name(char * user_input) {char terminal_name[255];struct stat stat_buffer;if (lstat(user_input, &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 * result = (char *) malloc(sizeof(char) * 255);char *mytty = ttyname(0); /* begins "/dev/" */char *ttydev = mytty + strlen("/dev/");printf("%s\n", mytty);while ((utmp_pointer = getutent()) != NULL) {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;}

自己動手寫shell命令之write

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.