您的位置:首页 > 娱乐 > 明星 > Linux网络协议.之 tcp,udp,socket网络编程(三).之多进程实现并发demon

Linux网络协议.之 tcp,udp,socket网络编程(三).之多进程实现并发demon

2024/12/23 16:58:04 来源:https://blog.csdn.net/rjszcb/article/details/140955087  浏览:    关键词:Linux网络协议.之 tcp,udp,socket网络编程(三).之多进程实现并发demon

一、fork创建进程,来实现多并发
这只是个demon,并不能用于实际项目,多进程,消耗太多资源。没有人这么玩

1、服务端代码:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>int main(int argc,char **argv)
{int s_fd;int c_fd;int n_read;char readBuf[128];char msg[128] = {0};struct sockaddr_in s_addr;struct sockaddr_in c_addr;if(argc != 3){printf("param is not good\n");exit(-1);}memset(&s_addr,0,sizeof(struct sockaddr_in));memset(&c_addr,0,sizeof(struct sockaddr_in));//1.sockets_fd = socket(AF_INET,SOCK_STREAM,0);if(s_fd == -1){perror("socket");exit(-1);}s_addr.sin_family = AF_INET;s_addr.sin_port = htons(atoi(argv[2]));inet_aton(argv[1],&s_addr.sin_addr);//2.bindbind(s_fd,(struct sockaddr *)&s_addr,sizeof(struct sockaddr_in));//3.listen listen(s_fd,10);//4.acceptint clen = sizeof(struct sockaddr_in);while(1){c_fd = accept(s_fd,(struct sockaddr *)&c_addr,&clen);//父进程负责acceptif(c_fd == -1){perror("accept");}printf("get connect:%s\n",inet_ntoa(c_addr.sin_addr));if(fork() == 0)//创建一个子进程,来实现读写功能,父进程负责accept{if(fork() == 0)//创建一个子进程的子进程,来实现写功能{while(1){memset(msg,0,sizeof(msg));printf("input:");fgets(msg,sizeof(msg),stdin);write(c_fd,msg,strlen(msg));}}//5.readwhile(1)//子进程父进程,来实现读功能{memset(readBuf,0,sizeof(readBuf));n_read = read(c_fd,readBuf,128);if(n_read == -1){perror("read");}else{printf("get message:%d,%s\n",n_read,readBuf);}}break;}}return 0;
}

2、客户端代码:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>int main(int argc,char **argv)
{int c_fd;int n_read;char readBuf[128];//      char *msg = "msg form client";char msg[128] = {0};struct sockaddr_in c_addr;memset(&c_addr,0,sizeof(struct sockaddr_in));if(argc != 3){printf("parm is not good\n");exit(-1);}//1.socketc_fd = socket(AF_INET,SOCK_STREAM,0);if(c_fd == -1){perror("socket");exit(-1);}c_addr.sin_family = AF_INET;c_addr.sin_port = htons(atoi(argv[2]));inet_aton(argv[1],&c_addr.sin_addr);//2.connectif(connect(c_fd,(struct sockaddr *)&c_addr,sizeof(struct sockaddr)) == -1){perror("connect");exit(-1);}if(fork() == 0)//创建一个子进程,来实现写功能{while(1){memset(msg,0,sizeof(msg));printf("input:");fgets(msg,sizeof(msg),stdin);write(c_fd,msg,strlen(msg));}}while(1)//父进程进程,来实现读功能{memset(readBuf,0,sizeof(readBuf));n_read = read(c_fd,readBuf,128);if(n_read == -1){perror("read");}else{printf("get message form server:%d,%s\n",n_read,readBuf);}}return 0;
}       

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com