Advertisement
Advertisement
| 03.18.2008 at 09:40AM PDT, ID: 23250824 |
|
[x]
Attachment Details
|
||
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: |
/* my signal function */
void signal_handler(int sig)
{
pid_t pid;
int status;
switch(sig)
{
case SIGCHLD:
/* for solaris and unix system */
signal(SIGCHLD, signal_handler);
while( (pid = waitpid(-1,&status,WNOHANG)) > 0)
{
count--; /* child processes counter */
}
break;
case SIGTSTP:
printf("\nI'm quitting...\nGood Bye!\n");
exit(0);
break;
default:
// uups -- what's this?
puts("Unexpected signal received!\n");
break;
}
}
/* ..... */
sock = socket(AF_INET, SOCK_STREAM, 0); /* SOCK_STREAM per TCP; */
if (sock < 0) {
perror("Creating a stream socket");
exit(1);
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(port);
/* call SO_REUSEADDR before bind() */
value = 1;
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&value, sizeof(value)) < 0) {
perror("during setsockopt");
exit(5);
}
if (bind(sock, (struct sockaddr *) &server, sizeof(server)) < 0) {
perror("binding socket");
exit(2);
}
listen(sock, 2);
signal(SIGCHLD,SIG_IGN); /* to avoid zombies */
signal(SIGTSTP, signal_handler); /* trap signal for child processes on unix and solaris */
signal(SIGCHLD, signal_handler); /* trap CTRL-Z signal */
pid_t pid;
while (1) {
client_len = sizeof(client);
printf("\nServer in attesa\n");
if ((fd = accept(sock, (struct sockaddr *) &client, &client_len)) < 0) {
perror("accepting connection");
exit(3);
}
if ( count < child_max) {
count ++;
msg[0] = 0;
Writeline(fd, msg, 1);
if ( (pid = fork() == 0) ){ /* figlio */
/* guardiamo i dati del client */
gethostname(host, 40);
printf("Accepted client: IP= %s, port=%d, hostname= %s\n",
inet_ntoa(client.sin_addr),
ntohs(client.sin_port), host);
listen_client_requests(fd);
exit(0); /* when a child ends */
}
else
close(fd);
}
else if (count >= child_max){
msg[1] = 255;
Writeline(fd, msg, 1);
close(fd);
}
else {
close(fd);
/* padre chiude sempre fd */
}
}
return 0;
}
|