Linux下的並發網路服務器模型

19 篇文章 0 订阅
3 篇文章 0 订阅

openSUSE 11.4 - 2.6.37.1-1.2@x64編譯通過

 

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>

void str_ser(int sockfd);

int main(void)
{
    int sockfd = 0;
    int con_fd = 0;
    int new_fd = 0;
    int numbytes = 0;
    int ret = 0;
    int pid = 0;
    struct sockaddr_in my_addr = {0};
    struct sockaddr_in their_addr = {0};
    int sin_size = 0;
    char * buf = NULL;
   
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(0 > sockfd)
    {
        printf("error in socket!\n");
        return 0;
    }
   
    //
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(33333);
    my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    bzero(&(my_addr.sin_zero), 8);
   
    ret = bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));
    if(0 > ret)
    {
        printf("bind error!\n");
        return 0;
    }
   
    ret = listen(sockfd, 10);
    if(0 > ret)
    {
        printf("listen error!\n");
        return 0;
    }
   
    //
    while(1)
    {
        sin_size = sizeof(struct sockaddr_in);
        con_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
        if(0 > con_fd)
        {
            printf("accept error!\n");
            return 0;
        }
       
        pid = fork();  //派生子進程

        printf("forked!\n");

        if(0 > pid)
        {
            printf("fork error!\n");
            return 0;
        }

        //子進程
        if(0 == pid)
        {
            printf("0 == pid\n");
           
            close(sockfd);
            str_ser(con_fd);
           
            //
            close(con_fd);
            exit(0);
            //return 0;
        }
      
        //父進程
        printf("0 != pid\n");
        close(con_fd);
    }//end while

    printf("line = %u\n", __LINE__);
       
    close(sockfd);
    return 0;
}

void str_ser(int sockfd)
{
    char recvs[100] = {0};
    int n = 0;
    while(1)
    {
        n = recv(sockfd, recvs, 100, 0);
        if(0 == n)
      {
          return;
      }
     
      send(sockfd, recvs, n, 0);
    }
   
    return;
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值