您的位置:首页 > 运维架构 > Linux

Linux——高性能服务器编程,多进程编程

2017-11-17 21:07 211 查看
Linux——高性能服务器编程,多进程编程

多进程编程思路: 父进程只负责accept
---》fork,子进程负责和客户端进行通讯。
注意:
1、 父子进程共享文件描述符,所以创建出子进程后,没必要单独传递文件描述符。
2、 父进程创建出子进程后, 关闭accept返回的文件描述符。

服务器端代码 ser.c:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <signal.h>

void fun(int sign)
{
wait(NULL);
}

void main()
{
signal(SIGCHLD, fun);
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
assert(sockfd != -1);

struct sockaddr_in ser, cli;
memset(&ser, 0, sizeof(ser));
ser.sin_family = AF_INET;
ser.sin_port = htons(6500);
ser.sin_addr.s_addr = inet_addr("192.168.1.120");

int res = bind(sockfd, (struct sockaddr*)&ser, sizeof(ser));
assert(res != -1);

listen(sockfd, 5);

while(1)
{
int len = sizeof(cli);
int c = accept(sockfd, (struct sockaddr*)&cli, &len);
if(c < 0)
{
printf("error\n");
continue;
}

pid_t n = fork();
assert(n != -1);
if(n == 0)
{
while(1)
{
char buff[128] = {0};
int n = recv(c, buff, 127, 0);
if(n <= 0)
{
break;
}
printf("addr::%s   port::%d\n",
inet_ntoa(cli.sin_addr), ntohs(cli.sin_port));
printf("%s\n", buff);
send(c, "OK", 2, 0);
}

printf("%d unlink\n", c);
close(c);
exit(0);
}

close(c);
}
}


客户端代码  cli.c:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <fcntl.h>

void main()
{
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
assert(sockfd != -1);

struct sockaddr_in ser, cli;
memset(&ser, 0, sizeof(ser));
ser.sin_family = AF_INET;
ser.sin_port = htons(6500);
ser.sin_addr.s_addr = inet_addr("192.168.1.120");

int res = connect(sockfd, (struct sockaddr*)&ser, sizeof(ser));
assert(res != -1);

while(1)
{
printf("please input: ");
fflush(stdout);
char buff[128] = {0};
fgets(buff, 128, stdin);
if(strncmp(buff, "end", 3) == 0)
{
close(sockfd);
break;
}

send(sockfd, buff, strlen(buff) - 1, 0);
memset(buff, 0, 128);
recv(sockfd, buff, 127, 0);
printf("%s\n", buff);
}
}


运行结果:



可以支持多个客户端同时访问
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: