X-Git-Url: https://gapil.gnulinux.it/gitweb/?p=gapil.git;a=blobdiff_plain;f=listati%2FTCP_echod.c;h=d5c8bba93c29bd192f8021ec45ca687c036582a6;hp=3f17baaadca46d4b39da87610dc3ceeede1ca9b2;hb=12b230ea57ff3a54a12d4e2226e3901a2345fb63;hpb=1819cf252941f57e22a4836315c1399626d04bd5 diff --git a/listati/TCP_echod.c b/listati/TCP_echod.c index 3f17baa..d5c8bba 100644 --- a/listati/TCP_echod.c +++ b/listati/TCP_echod.c @@ -1,62 +1,28 @@ int main(int argc, char *argv[]) { - int list_fd, conn_fd; - pid_t pid; - struct sockaddr_in serv_add; ... - /* create socket */ - if ( (list_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { - perror("Socket creation error"); - exit(1); - } - /* initialize address and bind socket */ - memset((void *)&serv_add, 0, sizeof(serv_add)); /* clear server address */ - serv_add.sin_family = AF_INET; /* address type is INET */ - serv_add.sin_port = htons(7); /* echo port is 7 */ - serv_add.sin_addr.s_addr = htonl(INADDR_ANY); /* connect from anywhere */ - if (bind(list_fd, (struct sockaddr *)&serv_add, sizeof(serv_add)) < 0) { - perror("bind error"); - exit(1); - } - /* give away privileges and go daemon */ - if (setgid(65534) !=0) { /* first give away group privileges */ - perror("cannot give away group privileges"); - exit(1); - } - if (setuid(65534) !=0) { /* and only after user ... */ - perror("cannot give away user privileges"); - exit(1); - } - if (demonize) { /* go daemon */ - openlog(argv[0], 0, LOG_DAEMON); /* open logging */ - if (daemon(0, 0) != 0) { - perror("cannot start as daemon"); - exit(1); - } - } - /* main body */ - if (listen(list_fd, BACKLOG) < 0 ) { /* listen on socket */ - PrintErr("listen error"); - exit(1); - } - while (1) { /* handle echo to client */ - while (((conn_fd = accept(list_fd, NULL, NULL)) < 0) - && (errno == EINTR)); /* accept connection */ - if ( conn_fd < 0) { + ... + if (waiting) sleep(waiting); + /* handle echo to client */ + while (1) { + /* accept connection */ + while (((conn_fd = accept(list_fd, (struct sockaddr *)&cli_add, &len)) + < 0) && (errno == EINTR)); + if ( conn_fd < 0) { PrintErr("accept error"); exit(1); } - if ( (pid = fork()) < 0 ) { /* fork to handle connection */ - PrintErr("fork error"); - exit(1); - } - if (pid == 0) { /* child */ - close(list_fd); /* close listening socket */ - ServEcho(conn_fd); /* handle echo */ - exit(0); - } else { /* parent */ - close(conn_fd); /* close connected socket */ + if (debugging) { + inet_ntop(AF_INET, &cli_add.sin_addr, ipaddr, sizeof(ipaddr)); + snprintf(debug, MAXLINE, "Accepted connection form %s\n", ipaddr); + if (demonize) { + syslog(LOG_DEBUG, debug); + } else { + printf("%s", debug); + } } + /* fork to handle connection */ + ... + ... } - exit(0); /* normal exit, never reached */ }