dup 和 dup2既然有重定向的功能,那么我们之前写的tcp socket通信是不是可以修改一下呢?比如,不用write往socket里面写,而直接用dup2/dup重定向呢?
答案是肯定的。
代码如下
tcp_dup2_server
#include #include #include #include #include #include #include #include #include int startup(const char* _ip, int _port) { int sock = socket(AF_INET, SOCK_STREAM, 0); if(sock < 0) { perror("socket"); exit(2); } // bind绑定 struct sockaddr_in local; local.sin_family = AF_INET; local.sin_port = htons(_port); local.sin_addr.s_addr = inet_addr(_ip); if(bind(sock, (struct sockaddr*)&local, sizeof(local)) < 0) { perror("bind---"); exit(3); } if(listen(sock, 10) < 0) { perror("listen"); exit(4); } return sock; } static void usage(const char *proc) { printf("%s[ip][port]\n", proc); } int main(int argc, char *argv[]) { if(argc != 3) { usage(argv[0]); return 1; } //int sock =startup(argv[1], atoi(argv[2])); int listen_sock =startup(argv[1], atoi(argv[2])); struct sockaddr_in remote; socklen_t len = sizeof(remote); char buf[1024]; sleep(2); while(1) { int sock = accept(listen_sock, (struct sockaddr*)&remote, &len); if(sock < 0) { perror("accept***************"); continue; } printf("client ip: %s, port: %d\n", inet_ntoa(remote.sin_addr), ntohs(remote.sin_port)); while(1) { ssize_t s = read(sock, buf, sizeof(buf)-1); if(s > 0) { buf[s] = 0; printf("client say# %s\n", buf); write(sock, buf, strlen(buf)); }else if(s == 0) { printf("client is lose"); break; } } } } tcp_dup2_client #include #include #include #include #include #include #include #include #include static void usage(const char *proc) { printf("%s[ip][port]\n", proc); } int main(int argc, char *argv[]) { if(argc != 3) { usage(argv[0]); return 1; } int sock = socket(AF_INET, SOCK_STREAM, 0); if(sock < 0) { perror("socket"); return 1; } struct sockaddr_in peer; peer.sin_family = AF_INET; peer.sin_port = htons(atoi(argv[2])); peer.sin_addr.s_addr = inet_addr(argv[1]); if(connect(sock, (struct sockaddr*)& peer, sizeof(peer)) < 0) { perror("connet"); return 3; } char buf[1024]; int ret = dup2(sock, 1); while(1) { // printf("please user enter:"); // fflush(stdout); ssize_t _s = read(0, buf, sizeof(buf)-1); if(_s > 0) { buf[_s-1] = 0; //write(sock, buf, sizeof(buf)-1); } printf("%s", buf); fflush(stdout); } close(sock); }
