Openwrt tcp_server
1.使用YDHSDK
2.main如下
make提示这个错误
"WNOHANG" undeclared
注意加入
#include <sys/types.h> #include <sys/wait.h>
1 //server 2 #include <stdio.h> 3 #include <sys/socket.h> 4 #include <arpa/inet.h> 5 #include <netinet/in.h> 6 #include <stdlib.h> 7 #include <string.h> 8 #include <unistd.h> 9 #include <errno.h> 10 #include <signal.h> 11 #include <sys/types.h> 12 #include <sys/wait.h> 13 14 #define SERVPORT 10000 15 #define MAXLINE 100 16 17 18 static void sig_chld(int signo) 19 { 20 pid_t pid; 21 int stat; 22 while( (pid = waitpid(-1, &stat, WNOHANG)) > 0) 23 printf("child %d terminated\n", pid); 24 return; 25 } 26 27 28 //read data from client, and write back to them 29 static void str_echo(int sockfd) 30 { 31 ssize_t n; 32 char buf[MAXLINE]; 33 again: 34 while( (n = read(sockfd, buf, MAXLINE)) > 0 ) 35 write(sockfd, buf, n); 36 37 if(n < 0 && errno ==EINTR) 38 goto again; 39 40 else if(n < 0 ) 41 printf("error\n"); 42 } 43 44 45 //int main(int argc, char** argv) 46 int main(int agrc,char* argv[]) 47 { 48 int listenfd, connfd; 49 socklen_t clilen; 50 pid_t childpid; 51 struct sockaddr_in servaddr, cliaddr; 52 53 if( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) 54 { 55 printf("socket fd error\n"); 56 return -1; 57 } 58 59 bzero(&servaddr, sizeof(servaddr)); 60 61 servaddr.sin_family = AF_INET; 62 servaddr.sin_addr.s_addr = htonl(INADDR_ANY); 63 servaddr.sin_port = htons(SERVPORT); 64 if( bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) <0 ) 65 { 66 printf("bind error\n"); 67 return -1; 68 } 69 70 int backlong = 0; 71 if(listen(listenfd, backlong) <0 ) 72 { 73 printf("listen error\n"); 74 return -1; 75 } 76 77 signal(SIGCHLD, sig_chld); 78 for(;;) 79 { 80 clilen = sizeof(cliaddr); 81 if( (connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen)) < 0) 82 { 83 if(errno == EINTR) continue; 84 else printf("accept error\n"); 85 return 0; 86 } 87 printf("accept \n"); 88 if( (childpid = fork()) == 0 ) 89 { 90 close(listenfd); //close child's listen socket 91 str_echo(connfd); 92 exit(0); 93 } 94 close(connfd); 95 } 96 }

浙公网安备 33010602011771号