現在,echoサーバに10進数を基数変換して表示するという機能を追加しようと試みています。
現在のソースは以下の通りです。
現在はユーザからの入力ではなく,
c
1int radix_conversion(int i, int s){ 2 3 num = 2; 4 radix = 2;
とあらかじめ数値を設定していますが,ユーザから数値を入力させて処理を'exit'など何らかのコマンドが入力されるまで続けたいです。
どのようにしたら実現できますでしょうか。
c
1#include <stdio.h> 2#include <time.h> 3#include <sys/types.h> 4#include <sys/socket.h> 5#include <netinet/in.h> 6#include <netdb.h> 7#include <errno.h> 8#include <err.h> 9#include <unistd.h> 10#include <string.h> 11#include <stdlib.h> 12#include <arpa/inet.h> 13#include<linux/if.h> 14#include<sys/ioctl.h> 15 16/*クライアントとの通信*/ 17int read_write(int s) { 18 socklen_t fromlen; 19 int i, n, ls, ret; 20 char buf[2048], buf2[2048], *buf3; 21 22 23 fd_set rfd, rfd0; 24 FD_ZERO(&rfd0); 25 FD_SET(s, &rfd0); 26 27 while (1) { 28 rfd = rfd0; 29 ret = select(FD_SETSIZE, &rfd, NULL, NULL, NULL); 30 if (ret < 0) { 31 perror("select"); 32 continue; 33 } 34 for (i = 0; i < FD_SETSIZE; i++) { 35 if (FD_ISSET(i, &rfd)) { 36 if ((ls = accept(i, NULL, NULL)) > 0) { 37 FD_SET(ls, &rfd0); 38 } 39 else { 40 n = read(i, buf, sizeof(buf)); 41 if (n < 0) { 42 perror("read"); 43 return -1; 44 } 45 if (strncmp("quit", buf, 4) == 0) { 46 close(i); 47 FD_CLR(i, &rfd0); 48 } 49 if (strncmp("radix_c", buf, 7) == 0) { 50 n = radix_conversion(i); 51 if (n < 1) { 52 perror("write"); 53 break; 54 } 55 break; 56 } 57 else { 58 buf[n - 2] = '\0'; 59 sprintf(buf2, "OK: %s\n", buf); 60 n = write(i, buf2, strlen(buf2) + 1); 61 if (n < 1) { 62 perror("write"); 63 break; 64 } 65 } 66 } 67 } 68 } 69 } 70 close(s); 71 return 0; 72} 73 74int radix_conversion(int i, int s) 75{ 76 unsigned num, radix; 77 char result[50]; 78 79 int n; 80 num = 2; 81 radix = 2; 82 static const char c_num[] = "0123456789abcdefghijklmnopqrstuvwxyz"; 83 char buf[33]; 84 85 int k = 0, j = 0; 86 87 88 89 do buf[k++] = c_num[num % radix]; while (num /= radix); 90 do result[j++] = buf[--k]; while (k != 0); 91 result[j] = '\0'; 92 93 94 /*書き込み*/ 95 n = write(i, result, strlen(result) + 1); 96 return n; 97 98} 99 100 101int main(int argc, char *argv[]) { 102 103 int s; 104 105 if (argc != 2) { 106 fprintf(stderr, "usage: %s port\n", argv[0]); 107 exit(1); 108 } 109 110 s = make_socket(&argv[1]); 111 112 read_write(s); 113 114 return 0; 115}