- 论坛徽章:
- 0
|
我才开始学习c,写了如下代码不知为什么子进程不退出,请编程高手帮忙,理论各实际有很大区别呀
#include <stdio.h>;
#include <stdlib.h>;
#include <netinet/in.h>;
//#include <sys/socket.h>;
#include <sys/time.h>;
#include <wait.h>;
#include <errno.h>;
static void sigchld_handler(int signo) {
pid_t pid;
int status;
while((pid = waitpid(-1,&status,WNOHANG)) >; 0) {;}
}
void haserror(char * msg) {
perror(msg);
exit(0);
}
int main() {
int pid;
int rc;
int fd;
int listen_sock;
int srv;
struct timeval tv;
fd_set readfds;
int port = 8000;
struct sockaddr_in tcpaddr;
tcpaddr.sin_family = AF_INET;
tcpaddr.sin_addr.s_addr = INADDR_ANY;
tcpaddr.sin_port = htons(port);
listen_sock = socket(AF_INET,SOCK_STREAM,IPPROTO_IP);
if (listen_sock == -1)
haserror("Socket create error");
rc = bind(listen_sock,(struct sockaddr *) &tcpaddr,sizeof(tcpaddr));
if (rc == -1)
haserror("Bind error");
rc = listen(listen_sock,128);
if (rc == -1)
haserror("listen error");
rc = fork();
if (rc == (pid_t) -1)
haserror("Fork failed");
else if (rc > 0) {
printf("Daemon start ok!\n");
exit(0);
} else {
signal(SIGCHLD, sigchld_handler);
printf ("listen_sock=%d\ttv.tv_sec=%d\ttv.tv_usec=%d\n", listen_sock, tv.tv_sec, tv.tv_usec);
for (;;) {
FD_ZERO(&readfds);
FD_SET(listen_sock, &readfds);
tv.tv_sec = 5;
tv.tv_usec = 0;
srv = select(listen_sock + 1, &readfds, NULL, NULL, &tv);
if (srv >; 0)
printf("srv=%d\n",srv);
if (!FD_ISSET(listen_sock, &readfds))
{
continue;
}
rc = fork();
if (rc == (pid_t) -1)
haserror("Fork failed");
else if (rc > 0)
continue;
for (;;)
{
struct sockaddr_in remote_addr;
int addr_size = sizeof(remote_addr);
int ap;
ap = accept(listen_sock, (struct sockaddr *) &remote_addr, &addr_size);
if (ap == -1) {
perror("accept failed");
exit(0);
} else {
int n;
char * buff;
close(listen_sock);
printf("test ok");
send(ap,"Children start ok", strlen("Children start ok")+1,0);
sleep(10);
buff = malloc(sizeof(char) * 4096);
memset(buff,0x0,4096);
n = recv(ap,buff,4096,0);
if (n == -1)
haserror("Can't get data");
else if (n == 0)
haserror("Connection closed by client");
printf("n=%d\n",n);
printf("buff=%s\n",buff);
free(buff);
close(ap);
break;
exit(0);
}
}
}
}
close (listen_sock);
}
[ 本帖最后由 guxing1841 于 2006-6-21 12:00 编辑 ] |
|