Linux網路編程(3)——多進程、多線程

來源:互聯網
上載者:User

標籤:環境   pthread   data   get   ack   實現   關閉   linux網路   turn   


在我的裡面已經介紹了linux以下c的進程、線程介面,這裡就不做過多闡述了。


多進程

這裡多進程採用傳統的多進程模型。每當有client發來的串連時建立一個進程來處理串連,一個子進程相應一個串連。

有了上篇單一進程的基礎,此處僅僅做簡單的改動便能夠實現。

    while(1){        clientfd = Accept(servfd, (struct sockaddr*)&cliaddr, &clientlen);        host = Gethostbyaddr((const char*)&cliaddr.sin_addr.s_addr, sizeof(cliaddr.sin_addr.s_addr), AF_INET);        printf("server connect to host: %s %s\n",host->h_name, inet_ntoa(cliaddr.sin_addr));        if ((child_pid = Fork()) == 0){            Close(servfd);            echo(clientfd);            Close(clientfd);        }        Close(clientfd);    }
僅僅須要在while裡面加入進程的建立就可以,然後在子進程裡先關閉父進程的監聽通訊端。

當然。不要忘了在上面加入Fork錯誤處理的包裹函數(在Fork一節中已講到)。

void error_msg(char *msg){    perror(msg);    exit(0);}int Fork(){    pid_t pid;    if ( ( pid = fork() ) < 0 )        error_msg("fork failed");    return pid;}

執行結果:

client:


server:

多線程

線程和進程在非常多方面是相通的,仿照上面的多進程的傳統模型。不難實現多線程的傳統模型。

依舊是在while裡面做簡單的改動就可以。

        clientfd = (int*)malloc(sizeof(int));        *clientfd = Accept(servfd, (struct sockaddr*)&cliaddr, &clientlen);        host = Gethostbyaddr((const char*)&cliaddr.sin_addr.s_addr, sizeof(cliaddr.sin_addr.s_addr), AF_INET);        printf("server connect to host: %s %s\n",host->h_name, inet_ntoa(cliaddr.sin_addr));        Pthread_create(&tid, NULL, &thread, clientfd);        Close(*clientfd);

使用malloc是為了避免因為多線程訪問了同樣的clientfd從而出現無法預估的後果,全部手動分配。

線程函數為

void *thread(void* arg){    int clientfd = *((int*)arg);    free(arg);    Pthread_detach(pthread_self());    echo(clientfd);    close(clientfd);    return NULL;}

執行結果:

這段代碼有個問題,clientfd傳入線程之後。arg指標沒有接收到值,指在了一個無法訪問的地方(gdb顯示值為0x00),百思不得其解。

(原理非常easy,遇到的問題先記錄下,假設有人知道錯在哪裡希望能指正出來。。

  環境 ubuntu 64位,編譯器gcc)


Linux網路編程(3)——多進程、多線程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.