静态进程池

proto.h
#ifndef PROTO_H_
#define PROTO_H_

#define SERVERPORT "2016"
#define FMT_STAMP "%lld\r\n"

#endif


client.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "proto.h"


int main(int argc,char **argv)
{
	int sd;
	sd = socket(AF_INET,SOCK_STREAM,0);
	struct sockaddr_in raddr;
	long long stamp;
	if(argc < 2)
	{
		fprintf(stderr,"Usage....\n");
		exit(1);
	}

	if(sd < 0)
	{
		perror("socket()");
		exit(1);
	}

//	bind();
	raddr.sin_family = AF_INET;
	raddr.sin_port = htons(atoi(SERVERPORT));
	inet_pton(AF_INET,argv[1],&raddr.sin_addr);

	if(connect(sd,(void *)&raddr,sizeof(raddr)) <0)
	{
		perror("connect()");
		exit(1);
	}

	//UNIX 一切皆文件

	FILE * fp;
	fp = fdopen(sd,"r");
	if(fp == NULL)
	{
		perror("fdopen()");
		exit(1);
	}
	if(fscanf(fp,FMT_STAMP,&stamp) <1)
	{
		fprintf(stderr,"Bad format!\n");
	}
	else
	{
		fprintf(stdout,"stamp = %lld\n",stamp);
	}

	//recv();
	//close();	

	exit(0);
}


server.c

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include "proto.h"

#define IPSTRSIZE 40
#define  BUFSIZE 1024
#define PROCNUM 4

static void server_loop(int sd);

static void server_job(int sd)
{
	char buf[BUFSIZE];
	int len;
	len  = sprintf(buf,FMT_STAMP,(long long)time(NULL));

	if(send(sd,buf,len,0)<0)
	{
		perror("send()");
		exit(1);
	}
}

int main()
{
	int sd;
	struct sockaddr_in laddr,raddr;	

	sd = socket(AF_INET,SOCK_STREAM,0);
	if(sd < 0)
	{
		perror("socket()");
		exit(1);
	}
	
	int val = 1;
	if(setsockopt(sd,SOL_SOCKET,SO_REUSEADDR,&val,sizeof(val))<0)
	{
		perror("setsockopt()");
		exit(1);
	}
	laddr.sin_family = AF_INET;
	laddr.sin_port = htons(atoi(SERVERPORT));
	inet_pton(AF_INET,"0.0.0.0",&laddr.sin_addr);

	if(bind(sd,(void *)&laddr,sizeof(laddr))<0)
	{
		perror("bind()");
		exit(1);
	}

	if(listen(sd,10)<0)
	{	
		perror("listen()");
		exit(1);
	}

	pid_t pid;
	int i;
	for(i =0;i<PROCNUM;i++)
	{
		pid = fork();
		if(pid < 0)
		{	
				perror("fork()");
				exit(1);
		}

		if(pid == 0)
		{
			server_loop(sd);
			exit(0);
		}
		
	}

	for(i=0;i<PROCNUM;i++)
	{
		wait(NULL);
	}
	close(sd);
	exit(0);

}

static void server_loop(int sd)
{
	struct sockaddr_in raddr;
	int newsd;
	char ipstr[IPSTRSIZE];
	socklen_t raddr_len;
	raddr_len = sizeof(socklen_t);
	while(1)
	{
		newsd = accept(sd,(void *)&raddr,&raddr_len);
		if(newsd <0)
		{
			perror("accept()");
			exit(1);
		}
		inet_ntop(AF_INET,&raddr.sin_addr,ipstr,IPSTRSIZE);
		printf("[%d]Client: %s:%d\n",getpid(),ipstr,ntohs(raddr.sin_port));
		
		server_job(newsd);
		close(newsd);
	}
	close(sd);
}

 

转载于:https://my.oschina.net/osyunwei/blog/734887

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值