#include "socket_includes.h"
#include <signal.h>
int mz_ipv4_tcp_create_socket(void)
{
int listenfd, sockfd, opt = 1;
struct sockaddr_in server, client;
socklen_t len;
int timep;
int ret;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
if(listenfd < 0){
perror("Create socket fail.");
return -1;
}
if((ret = setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) < 0){
perror("Error, set socket reuse addr failed");
return -1;
}
bzero(&server, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(SERV_PORT);
server.sin_addr.s_addr = htonl(INADDR_ANY);
len = sizeof(struct sockaddr);
if(bind(listenfd, (struct sockaddr *)&server, len)<0){
perror("bind error.");
return -1;
}
listen(listenfd, MAX_LISTEN_QUE);
return listenfd;
}
int mz_process_data(int sockfd)
{
int bytes;
char buf[MAX_BUFFER_SIZE], read_buf[MAX_BUFFER_SIZE];
memset(read_buf, 0x00, MAX_BUFFER_SIZE);
memset(buf, 0x00, MAX_BUFFER_SIZE);
while(1){
bytes = recv(sockfd, read_buf, 100, 0);
if(bytes < 0){
printf("read err.\n");
return -1;
}
if(bytes == 0){
printf("client connection closed.\n");
return 0;
}
printf("Bytes:%d\n", strlen(read_buf));
printf("read_buf: %x %x %x \n", read_buf[0], read_buf[1], read_buf[2]);
send(sockfd, read_buf, bytes, 0);
if(!strcmp(read_buf, "q")){
break;
}
if(!strcmp(read_buf, "c")){
printf("i love you.\n");
sprintf(read_buf, "%s","i love you.\n" );
send(sockfd, read_buf, bytes, 0);
}
}
close(sockfd);
return 0;
}
int mz_process_signal(int signo)
{
switch(signo){
case SIGCHLD:
printf("dddddddddd\n");
while(waitpid(-1, NULL, WNOHANG)>0);
break;
}
}
int mz_set_signal_handler(void)
{
struct sigaction act, oact;
act.sa_handler = (void *)mz_process_signal;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
act.sa_flags |= SA_RESTART;
if(sigaction(SIGCHLD, &act, &oact) < 0){
return -1;
}
return 0;
}
int main(int argc, char *argv[])
{
int listenfd, sockfd;
struct sockaddr_in server, client;
socklen_t len;
int bytes =0 ;
mz_set_signal_handler();
len = sizeof(struct sockaddr);
listenfd = mz_ipv4_tcp_create_socket();
while(1){
sockfd = accept(listenfd, (struct sockaddr *)&client, &len);
if(sockfd < 0){
perror("accept error.");
return -1;
}
printf("sockfd=%d\n", sockfd);
printf("IP: 0x%x, Port:%d\n", ntohl(client.sin_addr.s_addr), ntohs(client.sin_port));
if(fork() == 0){
close(listenfd);
mz_process_data(sockfd);
exit(0);
}
close(sockfd);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <fcntl.h>
#define MAX_LISTEN_QUE 5
#define SERV_PORT 8888
#define MAX_BUFFER_SIZE 100
子进程 并发
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...