🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: es.comp.os.linux.programacion
Article #7635

Re: Código base en C de un servidor

#7635
From: J.A. Gutierrez
Date: Tue, 04 Feb 2003 11:12
247 lines
6360 bytes
Antonio Maestre Garc�a <anmaegar@quitararrakis.es> wrote:
: J.A. Gutierrez wrote:

:> Antonio Maestre Garc�a <anmaegar@quitararrakis.es> wrote:
:> : atenci�n. Lo que haga el servidor es ya cosa m�a... Seguro q debe haber
:> : por ah� un c�digo base. En principio quiero evitar programarlo yo o
:> : tener que
:> 
:>
: ---------------------------------------------------------------------------
:> /*
:>  * <spd@daphne.cps.unizar.es>
:>  * Mon Apr 30 21:12:19 DST 2001
:>  *

: Antes q nada gracias. Solo he podido mirarlo 5 minutos (estoy de ex�menes),
: pero hay algo que no encuentro en ninguna parte mir�ndolo por encima... y
: es el tema de crear nuevos hilos por cada petici�n q le llega al servidor.
: �Est� eso implementado?

	si, mas o menos.
	Es decir, funcionalmente si (se encarga select()), pero estrictamente
	hablando no. Eso seria un servidor que utilice fork en lugar de
	select:


---------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>  /* atoi */
#include <unistd.h>  /* getpid */

#include <sys/types.h>  
#include <sys/socket.h> 
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>  

#include <signal.h>
#include <sys/wait.h>

#include <errno.h>  

int						s;
int						kids=0;
int						done;

void clean( int i );
void do_wait(int signal);

int main(int argc, char *argv[])
{
	double					n;
	long					n_p,nbytes;
	int						len;
	int						sockfd;
	int						clientlen;
	int						queue;
	struct sockaddr_in		server,
							client;
	FILE					*fd;
	char					buf[10000];
	char					*myname;
	char					*host;
	char					*user;

	char					hostname[256];
	struct  hostent			*hp;
	unsigned int			port;
	int						pid;

	if (argc!=2)
	{
		printf( "use: %s port\n", argv[0] );
		exit(1);
	}
	port = (unsigned int) atoi(argv[1]);

	memset(&server,0,sizeof(server));

	if (gethostname(hostname,sizeof(hostname)) < 0)
	{
		perror("gethostname: who am I ?");
		exit(1);
	}
	
	if ( (hp=gethostbyname(hostname)) == NULL)
	{
		perror("gethostbyname: can't get an address");
		exit(2);
	}

	server.sin_family =			AF_INET;
/*	server.sin_port=atoi(buf);*/
	server.sin_port =			htons(port);
/*	server.sin_addr.s_addr =	htonl(INADDR_ANY);*/
/*	server.sin_addr.s_addr =inet_addr(argv[1]);*/
	server.sin_addr.s_addr =	
		htonl( ((struct in_addr *)(hp->h_addr_list[0]))->s_addr );


	queue=3;

	if (( SIG_ERR == sigset(SIGTERM, clean)) ||
		( SIG_ERR == sigset(SIGINT, clean)) ||
		( SIG_ERR == sigset(SIGCHLD, do_wait))
		)
		perror("signal");


	if ( (s=socket(AF_INET,SOCK_STREAM,0)) == -1 )
	{
		perror("socket");
		exit(1);
	}

	if( bind( s, (struct sockaddr *)&server, sizeof(server)) != 0 )
	{	
		perror("bind");
		exit(1);
	}


	if ( listen( s, queue ) != 0 )
	{
		perror("listen");
		exit(1);
	}
		
	for(done=0; !done; )
	{
		fprintf(stderr,"%d accepting\n", getpid());

		if( ( sockfd = accept( s, 0, 0 ) ) < 0 )
		if ( errno != EINTR )
		{
			perror("accept");
			break;
		}
		else
			continue;

		switch(	pid = fork())
		{
			case -1:
				perror("fork");
				break;

			case 0:
				n =		0;
				n_p =	0;

				nbytes = recv(sockfd,buf,sizeof(buf),0);
				buf[nbytes]=0x00;
				write(sockfd,"ack\r\n",5);
			
			
				while(nbytes>0)
				{
					fprintf(stdout,"MSG: \"%s\"\n",buf);
					fflush(stdout);
					n +=	nbytes;
					n_p +=	1;
					nbytes = recv(sockfd,buf,sizeof(buf),0);
					buf[nbytes]=0x00;
					write(s,"ack\r\n",5);
				}
				printf("Rec: %.0f bytes   %.0ld packets\n",n,n_p);		

				fprintf(stderr,"die %d\n", getpid());
				close( s );

				exit(0);			
				break;
			
			default:
				fprintf(stderr, "%d spawned %d\n", ++kids, pid );
				fflush(stderr);
				break;
		}
	}

	while ( kids > 0 )
	{
		sigpause(SIGCLD);
		sighold(SIGCLD);
	}

	if ( s != 0 )
	{
		if ( -1 == close(s))
			perror("close");
	}


	exit(errno);
}

/************************************************************************/

void clean( int sig )
{
	if ( SIG_ERR == sigset(sig, clean))
		perror("clean:signal");

	fprintf(stderr,"%d a escaparrar (%d)\n", getpid(), sig);
	done=1;
}

void do_wait(int sig)
{
	int st;
	int wpid;
	

	wpid = wait ( &st );

	fprintf(stderr, "wait: died %d\n", wpid);
	if (WIFSTOPPED(st))
	{
		fprintf(stderr,"stoped %d\n", WSTOPSIG(st));
	}
	else if(WIFEXITED(st))
	{
		fprintf(stderr, "do_wait: %d exit with %d\n", wpid, WEXITSTATUS(st));
	}
	else if(WIFSIGNALED(st))
	{
		fprintf(stderr,"signaled %d\n", WTERMSIG(st));
	}
	if(st&0200)
		fprintf(stderr, "core dumped\n");


	fprintf(stderr, "do_wait: died %d\n", wpid);
	fprintf(stderr, "nkids %d\n", --kids);
	fflush(stderr);
	sigset(SIGCHLD, do_wait);
}

---------------------------------------------------------------------------


-- 
PGP and other useless info at      \
http://www.cps.unizar.es/~spd/      \
finger://daphne.cps.unizar.es/spd    \       Timeo Danaos et dona ferentes
ftp://ivo.cps.unizar.es/pub/          \                         (Virgilio)   
Technical Details
Message-ID: <b1o76l$ars$3@news.unizar.es>
Path: arc1-ca.pugleaf.net!archiver1.google.com!news1.google.com!newsfeed.stanford.edu!cyclone.bc.net!HSNX.atgi.net!newsfeed.frii.net!newsfeed.frii.net!news-out.newsfeeds.com!propagator2-maxim!news-in.spamkiller.net!news.telia-iberia.com!bashful.rediris.es!news.unizar.es!not-for-mail
References: <3e3bbbab_1@news.arrakis.es> <b1lnbd$8o0$1@news.unizar.es> <3e3f0179_2@news.arrakis.es>

Show Full Headers
Complete Article Headers
X-Google-Language: SPANISH,ASCII
X-Google-Thread: f86c8,79de37df9f28b12c
X-Google-Attributes: gidf86c8,public
X-Google-ArrivalTime: 2003-02-04 02:34:41 PST
Path: arc1-ca.pugleaf.net!archiver1.google.com!news1.google.com!newsfeed.stanford.edu!cyclone.bc.net!HSNX.atgi.net!newsfeed.frii.net!newsfeed.frii.net!news-out.newsfeeds.com!propagator2-maxim!news-in.spamkiller.net!news.telia-iberia.com!bashful.rediris.es!news.unizar.es!not-for-mail
From: "J.A. Gutierrez" <spd@daphne.cps.unizar.es>
Newsgroups: es.comp.os.linux.programacion
Subject: Re: Código base en C de un servidor
Date: 4 Feb 2003 11:12:21 GMT
Organization: Rank
Lines: 247
Message-ID: <b1o76l$ars$3@news.unizar.es>
References: <3e3bbbab_1@news.arrakis.es> <b1lnbd$8o0$1@news.unizar.es> <3e3f0179_2@news.arrakis.es>
NNTP-Posting-Host: daphne.cps.unizar.es
Mime-Version: 1.0
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 8bit
X-Trace: news.unizar.es 1044357141 11132 155.210.152.20 (4 Feb 2003 11:12:21 GMT)
X-Complaints-To: usenet@news.unizar.es
NNTP-Posting-Date: 4 Feb 2003 11:12:21 GMT
User-Agent: tin/1.4.5-20010409 ("One More Nightmare") (UNIX) (IRIX/6.2 (IP22))