Minor Problem With Fork And Listen
I am having 2 problems with the following C code. First of which is reguardless to which port number i assign it, it always trys to bind to port 2586. The second problem is that over time it builds up debunked processes (Z) that never terminate until the parent is terminated. Any help, or general suggestions would be greatly appreciated.
Code:
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
int terminate=0;
void signalhd(int senal);
int main()
{
struct sockaddr_in sin, fsin;
int s, ssock, alen;
char *ipaddress;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_port = 6666;
if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{
perror("Cant create socket");
exit(1);
}
if (bind(s, (struct sockaddr *)&sin, sizeof sin) < 0)
{
perror("Cant assign addres");
exit(2);
}
if (listen(s, 5) < 0)
{
perror("Cant turn to listening mode");
exit(3);
}
signal (SIGCHLD, SIG_IGN);
signal (SIGINT,signalhd);
while (1)
{
if (terminate==1)
{
close(s);
exit(0);
}
alen = sizeof(fsin);
if ((ssock=accept(s, (struct sockaddr *)&fsin, &alen)) < 0)
{
if (errno == EINTR) continue;
perror("Accept failed");
exit(4);
}
switch (fork()) {
case -1:{
perror ("Forking error");
exit (5);
}
case 0: {
close(s);
exit(0);
}
default: {
ipaddress=(char *)inet_ntoa(fsin.sin_addr);
write(ssock, ipaddress, strlen(ipaddress));
close(ssock);
break;
}
}
}
return 0;
}
void signalhd(int senal){
if (senal==SIGINT){
printf("...Interrupt...\n");
terminate=1;
}
}