Linux 基于父子进程的TCP服务器应用编程

#include 
#include 
#include 
#include 
#include 

#define PORTNUM 3333

int main()
{
    int sockfd,sock_fd,ret,readbytes;
    char buf[512];
    struct sockaddr_in my_addr,your_addr;
    int addrlen = sizeof(struct sockaddr);
    //socket
    sockfd = socket(AF_INET,SOCK_STREAM,0);

    if(sockfd == -1)
    {
        printf("socket error\n");
    }

    //bind
    bzero(&my_addr,sizeof(struct sockaddr_in));
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(PORTNUM);
    my_addr.sin_addr.s_addr = inet_addr("192.168.110.110");
    ret = bind(sockfd,(struct sockaddr*)&my_addr,addrlen);
    
    if(ret < 0)
    {
        printf("bind error\n");
    }

    //listen
    listen(sockfd,10);
    while(1)
    {
        //accept
	sock_fd = accept(sockfd,NULL,NULL);

	if(sock_fd < 0)
	{
	    printf("accept error\n");
	}
	if(fork() == 0)
	{
	    readbytes = recv(sock_fd,buf,512,0);
	    buf[readbytes] = '\0';
	    printf("buf is %s\n",buf);
	    close(sock_fd);
	    close(sockfd);
	    exit(0);
	}

	else
	{
	    close(sock_fd);
	}

	//recv
    }

}

你可能感兴趣的:(Linux)