TCP网络编程中多线程的客户端实现(linux下)

TCP网络编程中多线程的客户端实现(linux下)

示例如下:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 


void sig_child(int signo)
{
        while(waitpid(-1,NULL,WNOHANG) > 0);
        return ;
}


int port = 8000;
int main()
{
        struct sockaddr_in sin,pin;
        int sock_descriptor,temp_sock_descriptor;
        socklen_t address_size;
        int i ,len,pid,on =1;
        char buf[16384];

        signal(SIGCHLD,sig_child);

        sock_descriptor = socket(AF_INET,SOCK_STREAM,0);
        bzero(&sin,sizeof(sin));
        sin.sin_family = AF_INET;
        sin.sin_addr.s_addr = INADDR_ANY;
        sin.sin_port = htons(port);
        setsockopt(sock_descriptor,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
        if( bind(sock_descriptor,(struct sockaddr *)&sin,sizeof(sin)) == -1 )
        {
                perror("call to bind\n");
                exit(1);
        }
        if(listen(sock_descriptor,20) == -1)
        {
                perror("call to listen\n");
                exit(1);
        }
        printf("accepting connections...\n");

        while(1)
        {
                temp_sock_descriptor = accept(sock_descriptor,(struct sockaddr *)&pin,&address_size);
                if( (pid = fork()) < 0 )
                {
                        perror("fork");
                        exit(1);
                }
                else if(pid == 0)
                {//child
                        close(sock_descriptor);
                        if(recv(temp_sock_descriptor,buf,16384,0) == -1)
                        {
                                perror("call to recv\n");
                                exit(1);
                        }
                        printf("received from client :%s\n",buf);


                        len = strlen(buf);
                        for( i  = 0 ; i < len ; i++)
                        {
                                buf[i] = toupper(buf[i]);
                        }
                        if(send(temp_sock_descriptor,buf,len+1,0) == -1)
                        {
                                perror("call to send \n");
                                exit(1);
                        }
                        sleep(60);
                        close(temp_sock_descriptor);
                        exit(0);
                }
                close(temp_sock_descriptor);
        }



}



注意:

1、由于父进程并不需要连接套接字,所以需要在父进程中关闭。同理,子进程不需要监听套接字,因此在子进程中关闭。

2、子进程在结束时会向父进程递送SIGCHLD信号,所以在父进程中捕获SIGCHLD信号,并在该信号处理程序中调用waitpid,从而防止僵尸进程的产生。

 

 

你可能感兴趣的:(C语言,网络)