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

來源:互聯網
上載者:User

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;}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.