多進程併發編程

exit()函數用於終止調用進程。關閉所有子進程打開的描述符,向父進程發送SIGCHLD信號,並返回狀態。
父進程可通過調用wait()或waitpid()函數獲得子進程的終止信息。

{
    if(listen(listenfd,BACKLOG)== -1){  
    perror("listen() error\n");  
    exit(1);  
    }  
    len=sizeof(client);  

    while(1)  
    {  
        if ((connfd =accept(listenfd,(struct sockaddr *)&client,&len))==-1) {  
            perror("accept() error\n");  
            exit(1);  
        }  
        if ((pid=fork())>0)
        {   
            //父進程需要關閉已建立連接的套接字,然後繼續等待接受其他連接  
            close(connfd);  
            continue;  
        }  
        else if (pid==0) 
        {
            //子進程需要關閉父進程中的監聽套接字,處理建立連接的套接字收發數據  
            close(listenfd);  
            process_cli(connfd, client);  
            exit(0);  
        }  
        else {  
            printf("fork()error\n");  
            exit(0);  
        }  
    }  
    close(listenfd);  
}  

多進程併發服務器編程

void pthread_exit(void*status);
指針status:指向線程的退出狀態。不能指向一個局部變量,因爲線程終止時其所有的局部變量將被撤銷。
還有其他兩種方法可使線程終止:
(1)啓動線程的函數pthread_create()的第3個參數返回。其返回值便是線程的終止狀態;
(2)如果進程的main()函數返回,或者當前進程中,任一線程調用了exit()函數,將終止該進程中所有線程。

【實例】

{
    if(listen(listenfd,BACKLOG)== -1){  
        perror("listen()error\n");  
        exit(1);  
    }  

    len=sizeof(client);  
    while(1)  
    {  
        //接受客戶端發過來的連接請求(阻塞到有連接請求)
        if ((connfd =accept(listenfd,(struct sockaddr *)&client,&len))==-1) {  
            perror("accept() error\n");  
            exit(1);  
        }  
        arg = (struct ARG *)malloc(sizeof(struct ARG));  
        arg->connfd =connfd;  
        memcpy((void*)&arg->client, &client, sizeof(client));  

        //創建線程來執行發送、接收的動作
        if(pthread_create(&tid, NULL, function, (void*)arg)) {  
            perror("Pthread_create() error");  
            exit(1);  
        }  
    }

    close(listenfd); 
}

多線程併發服務器編程

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章