1. 程式人生 > >2018-2019-1 20165233 實驗三 實時系統

2018-2019-1 20165233 實驗三 實時系統

實驗三 實時系統

任務一:

  • 學習使用Linux命令wc(1)

  • 基於Linux Socket程式設計實現wc(1)伺服器(埠號是你學號的後6位)和客戶端

  • 客戶端傳一個文字檔案給伺服器

  • 伺服器返加文字檔案中的單詞數

實驗步驟:

  • 利用命令列man 1 wc檢視命令wc(1)的內容。

  • 實現程式碼如下:

伺服器端

#include<netinet/in.h>  // sockaddr_in  
#include<sys/types.h>   // socket  
#include<sys/socket.h>  // socket  
#include<stdio.h>       // printf  
#include<stdlib.h>      // exit  
#include<string.h>      // bzero  

#define SERVER_PORT 165233
#define LENGTH_OF_LISTEN_QUEUE 20  
#define BUFFER_SIZE 1024
#define FILE_NAME_MAX_SIZE 512  
#define BEGIN 1; 

int main(void)  
{  

struct sockaddr_in server_addr;  
bzero(&server_addr, sizeof(server_addr));  
server_addr.sin_family = AF_INET;  
server_addr.sin_addr.s_addr = htons(INADDR_ANY);  
server_addr.sin_port = htons(SERVER_PORT);  

int server_socket_fd = socket(PF_INET, SOCK_STREAM, 0);  
if(server_socket_fd < 0)  
{  
    perror("Create Socket Failed:");  
    exit(1);  
}  
int opt = 1;  
setsockopt(server_socket_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));  

if(-1 == (bind(server_socket_fd, (struct sockaddr*)&server_addr, sizeof(server_addr))))  
{  
    perror("Server Bind Failed:");  
    exit(1);  
}  
    
if(-1 == (listen(server_socket_fd, LENGTH_OF_LISTEN_QUEUE)))  
{  
    perror("Server Listen Failed:");  
    exit(1);  
}  

while(1)  
{  
    struct sockaddr_in client_addr;  
    socklen_t client_addr_length = sizeof(client_addr);  

    int new_server_socket_fd = accept(server_socket_fd, (struct sockaddr*)&client_addr, &client_addr_length);  
    if(new_server_socket_fd < 0)  
    {  
        perror("Server Accept Failed:");  
        break;  
    }  


    char buffer[BUFFER_SIZE];  
    bzero(buffer, BUFFER_SIZE);  
    if(recv(new_server_socket_fd, buffer, BUFFER_SIZE, 0) < 0)  
    {  
        perror("Server Recieve Data Failed:");  
        break;  
    }  


    char file_name[FILE_NAME_MAX_SIZE+1];  
    bzero(file_name, FILE_NAME_MAX_SIZE+1);  
    strncpy(file_name, buffer, strlen(buffer)>FILE_NAME_MAX_SIZE?FILE_NAME_MAX_SIZE:strlen(buffer));  
    printf("%s\n", file_name);  


    FILE *fp = fopen(file_name, "w");  
    if(NULL == fp)  
    {  
        printf("File:\t%s Can Not Open To Write\n", file_name);  
        exit(1);  
    }  


    bzero(buffer, BUFFER_SIZE);  
    int length = 0;  
    while((length = recv(new_server_socket_fd, buffer, BUFFER_SIZE, 0)) > 0)  
    {  
    if(strcmp(buffer,"OK")==0) break;
        if(fwrite(buffer, sizeof(char), length, fp) < length)  
        {  
            printf("File:\t%s Write Failed\n", file_name);  
            break;  
        }  
        bzero(buffer, BUFFER_SIZE);  
    }  

    printf("Receive File:\t%s From Client IP Successful!\n", file_name);  
    fclose(fp);

int words=0;
char s[100];
FILE *fp2;
if((fp2=fopen(file_name,"r"))==NULL){
    printf("ERROR!\n");
    exit(0);
}
while(fscanf(fp2,"%s",s)!=EOF)
    words++;
fclose(fp2);
printf("%d words.\n",words);

char sendbuf[50];
sprintf(sendbuf,"%d",words);

send(new_server_socket_fd,sendbuf,50,0);

    close(new_server_socket_fd);  
}  

close(server_socket_fd);  
return 0;  
}

客戶端

#include<netinet/in.h>   // sockaddr_in  
#include<sys/types.h>    // socket  
#include<sys/socket.h>   // socket  
#include<stdio.h>        // printf  
#include<stdlib.h>       // exit  
#include<string.h>       // bzero  

#define SERVER_PORT 165233  
#define BUFFER_SIZE 1024  
#define FILE_NAME_MAX_SIZE 512  
#define BEGIN 1;

int main()  
{  

struct sockaddr_in client_addr;  
bzero(&client_addr, sizeof(client_addr));  
client_addr.sin_family = AF_INET;  
client_addr.sin_addr.s_addr = htons(INADDR_ANY);  
client_addr.sin_port = htons(0);  

int client_socket_fd = socket(AF_INET, SOCK_STREAM, 0);  
if(client_socket_fd < 0)  
{  
    perror("Create Socket Failed:");  
    exit(1);  
}  

if(-1 == (bind(client_socket_fd, (struct sockaddr*)&client_addr, sizeof(client_addr))))  
{  
    perror("Client Bind Failed:");  
    exit(1);  
}  

struct sockaddr_in server_addr;  
bzero(&server_addr, sizeof(server_addr));  
server_addr.sin_family = AF_INET;  
if(inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) == 0)  
{  
    perror("Server IP Address Error:");  
    exit(1);  
}  
server_addr.sin_port = htons(SERVER_PORT);  
socklen_t server_addr_length = sizeof(server_addr);  

if(connect(client_socket_fd, (struct sockaddr*)&server_addr, server_addr_length) < 0)  
{  
    perror("Can Not Connect To Server IP:");  
    exit(0);  
}  

char file_name[FILE_NAME_MAX_SIZE+1];  
bzero(file_name, FILE_NAME_MAX_SIZE+1);  

printf("Please Input File Name On Client:\t");
scanf("%s", file_name);  

char buffer[BUFFER_SIZE];  
bzero(buffer, BUFFER_SIZE);  
strncpy(buffer, file_name, strlen(file_name)>BUFFER_SIZE?BUFFER_SIZE:strlen(file_name));  
  
if(send(client_socket_fd, buffer, BUFFER_SIZE, 0) < 0)  
{  
    perror("Send File Name Failed:");  
    exit(1);  
}  

    FILE *fp = fopen(file_name, "r");  
    if(NULL == fp)  
    {  
        printf("File:%s Not Found\n", file_name);  
    }  
    else  
    {  
        bzero(buffer, BUFFER_SIZE);  
        int length = 0;  
        while((length = fread(buffer, sizeof(char), BUFFER_SIZE, fp)) > 0)  
        {  
            if(send(client_socket_fd, buffer, length, 0) < 0)  
            {  
                printf("Send File:%s Failed./n", file_name);  
                break;  
            }  
            bzero(buffer, BUFFER_SIZE);  
        }  

        fclose(fp);  
        printf("File:%s Transfer Successful!\n", file_name);  
    }  

char s[50];
scanf("%s",s);
send(client_socket_fd,"OK",50,0);

char recvdata[sizeof(int)+1];
recv(client_socket_fd,recvdata,sizeof(int),0);
recvdata[sizeof(int)]='\0';
int words=atoi(recvdata);
close(client_socket_fd);  
return 0;  
}
  • 先執行開啟伺服器端,再執行開啟客戶端,可分別統計出文字test1test2的字數

任務二:

  • 使用多執行緒實現wc伺服器並使用同步互斥機制保證計數正確

  • 對比單執行緒版本的效能,並分析原因

實驗步驟:

  • 程式碼實現如下:

伺服器端

#include<stdlib.h>
#include<pthread.h>
#include<sys/socket.h>
#include<sys/types.h>       //pthread_t , pthread_attr_t and so on.
#include<stdio.h>
#include<netinet/in.h>      //structure sockaddr_in
#include<arpa/inet.h>       //Func : htonl; htons; ntohl; ntohs
#include<assert.h>          //Func :assert
#include<string.h>          //Func :memset
#include<unistd.h>          //Func :close,write,read
#define SOCK_PORT 165233
#define BUFFER_LENGTH 1024
#define MAX_CONN_LIMIT 512     //MAX connection limit

static void Data_handle(void * sock_fd);   //Only can be seen in the file

int main()
{
    int sockfd_server;
    int sockfd;
    int fd_temp;
    struct sockaddr_in s_addr_in;
    struct sockaddr_in s_addr_client;
    int client_length;

    sockfd_server = socket(AF_INET,SOCK_STREAM,0);  //ipv4,TCP
    assert(sockfd_server != -1);

    //before bind(), set the attr of structure sockaddr.
    memset(&s_addr_in,0,sizeof(s_addr_in));
    s_addr_in.sin_family = AF_INET;
    s_addr_in.sin_addr.s_addr = htonl(INADDR_ANY);  //trans addr from uint32_t host byte order to network byte order.
    s_addr_in.sin_port = htons(SOCK_PORT);          //trans port from uint16_t host byte order to network byte order.
    fd_temp = bind(sockfd_server,(struct scokaddr *)(&s_addr_in),sizeof(s_addr_in));
    if(fd_temp == -1)
    {
        fprintf(stderr,"bind error!\n");
        exit(1);
    }

    fd_temp = listen(sockfd_server,MAX_CONN_LIMIT);
    if(fd_temp == -1)
    {
        fprintf(stderr,"listen error!\n");
        exit(1);
    }

    while(1)
    {
        printf("waiting for new connection...\n");
        pthread_t thread_id;
        client_length = sizeof(s_addr_client);

        //Block here. Until server accpets a new connection.
        sockfd = accept(sockfd_server,(struct sockaddr_*)(&s_addr_client),(socklen_t *)(&client_length));
        if(sockfd == -1)
        {
            fprintf(stderr,"Accept error!\n");
            continue;                               //ignore current socket ,continue while loop.
        }
        printf("A new connection occurs!\n");
        if(pthread_create(&thread_id,NULL,(void *)(&Data_handle),(void *)(&sockfd)) == -1)
        {
            fprintf(stderr,"pthread_create error!\n");
            break;                                  //break while loop
        }
    }

    //Clear
    int ret = shutdown(sockfd_server,SHUT_WR); //shut down the all or part of a full-duplex connection.
    assert(ret != -1);

    printf("Server shuts down\n");
    return 0;
}

static void Data_handle(void * sock_fd)
{
    int fd = *((int *)sock_fd);
    int i_recvBytes;
    char data_recv[BUFFER_LENGTH];
    const char * data_send = "Server has received your request!\n";

    while(1)
    {
        printf("waiting for request...\n");
        //Reset data.
        memset(data_recv,0,BUFFER_LENGTH);

        i_recvBytes = read(fd,data_recv,BUFFER_LENGTH);
        if(i_recvBytes == 0)
        {
            printf("Maybe the client has closed\n");
            break;
        }
        if(i_recvBytes == -1)
        {
            fprintf(stderr,"read error!\n");
            break;
        }
        if(strcmp(data_recv,"quit")==0)
        {
            printf("Quit command!\n");
            break;                           //Break the while loop.
        }
        /*printf("read from client : %s\n",data_recv);
        if(write(fd,data_send,strlen(data_send)) == -1)
        {
            break;
        }*/
    }

    //Clear
    printf("terminating current client_connection...\n");
    close(fd);            //close a file descriptor.
    pthread_exit(NULL);   //terminate calling thread!
}

客戶端

#include<netinet/in.h>   // sockaddr_in  
#include<sys/types.h>    // socket  
#include<sys/socket.h>   // socket  
#include<stdio.h>        // printf  
#include<stdlib.h>       // exit  
#include<string.h>       // bzero  
  
#define SERVER_PORT 165233  
#define BUFFER_SIZE 1024  
#define FILE_NAME_MAX_SIZE 512  
  
int main()  
{  
    // 宣告並初始化一個客戶端的socket地址結構  
    struct sockaddr_in client_addr;  
    bzero(&client_addr, sizeof(client_addr));  
    client_addr.sin_family = AF_INET;  
    client_addr.sin_addr.s_addr = htons(INADDR_ANY);  
    client_addr.sin_port = htons(0);  
  
    // 建立socket,若成功,返回socket描述符  
    int client_socket_fd = socket(AF_INET, SOCK_STREAM, 0);  
    if(client_socket_fd < 0)  
    {  
        perror("Create Socket Failed:");  
        exit(1);  
    }  
  
    // 繫結客戶端的socket和客戶端的socket地址結構 非必需  
    if(-1 == (bind(client_socket_fd, (struct sockaddr*)&client_addr, sizeof(client_addr))))  
    {  
        perror("Client Bind Failed:");  
        exit(1);  
    }  
  
    // 宣告一個伺服器端的socket地址結構,並用伺服器那邊的IP地址及埠對其進行初始化,用於後面的連線  
    struct sockaddr_in server_addr;  
    bzero(&server_addr, sizeof(server_addr));  
    server_addr.sin_family = AF_INET;  
    if(inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) == 0)  
    {  
        perror("Server IP Address Error:");  
        exit(1);  
    }  
    server_addr.sin_port = htons(SERVER_PORT);  
    socklen_t server_addr_length = sizeof(server_addr);  
  
    // 向伺服器發起連線,連線成功後client_socket_fd代表了客戶端和伺服器的一個socket連線  
    if(connect(client_socket_fd, (struct sockaddr*)&server_addr, server_addr_length) < 0)  
    {  
        perror("Can Not Connect To Server IP:");  
        exit(0);  
    }  
  
    // 輸入檔名,並放到緩衝區buffer中等待發送  
    char file_name[FILE_NAME_MAX_SIZE+1];  
    bzero(file_name, FILE_NAME_MAX_SIZE+1);  

    printf("Please Input File Name On Client:\t");
    scanf("%s", file_name);  
  
    char buffer[BUFFER_SIZE];  
    bzero(buffer, BUFFER_SIZE);  
    strncpy(buffer, file_name, strlen(file_name)>BUFFER_SIZE?BUFFER_SIZE:strlen(file_name));  
      
    // 向伺服器傳送buffer中的資料  
    if(send(client_socket_fd, buffer, BUFFER_SIZE, 0) < 0)  
    {  
        perror("Send File Name Failed:");  
        exit(1);  
    }  
  
    
    // 開啟檔案並讀取檔案資料  
        FILE *fp = fopen(file_name, "r");  
        if(NULL == fp)  
        {  
            printf("File:%s Not Found\n", file_name);  
        }  
        else  
        {  
            bzero(buffer, BUFFER_SIZE);  
            int length = 0;  
            // 每讀取一段資料,便將其傳送給伺服器,迴圈直到檔案讀完為止  
            while((length = fread(buffer, sizeof(char), BUFFER_SIZE, fp)) > 0)  
            {  
                if(send(client_socket_fd, buffer, length, 0) < 0)  
                {  
                    printf("Send File:%s Failed./n", file_name);  
                    break;  
                }  
                bzero(buffer, BUFFER_SIZE);  
            }  
  
            // 關閉檔案  
            fclose(fp);  
            printf("File:%s Transfer Successful!\n", file_name);  
        }  

    
    /*char recvbuf[50];
    recv(client_socket_fd,recvbuf,50,0);    
    printf("%d words.\n",atoi(recvbuf));*/

    /*int words=0;
    recv(client_socket_fd,&words,sizeof(words),0);
    printf("%d words.\n",words);*/

    
    int count=0;
    char s[100];
    FILE *fp2;
    if((fp2=fopen(file_name,"r"))==NULL){
        printf("ERROR!\n");
        exit(0);
    }
    while(fscanf(fp2,"%s",s)!=EOF)
        count++;
    fclose(fp2);
    printf("%d words.\n",count);
    

    close(client_socket_fd);  
    return 0;  
} 
  • 在編譯多執行緒的程式碼時,gcc命令後要多加一個-lpthread的引數。

  • 先執行啟動伺服器端,再同步執行啟動兩個客戶端,分別統計test.txttest2.txt的字數。執行結果如下:

  • 對比單執行緒版本的效能,並分析原因:

單執行緒穩定,易於實現;多執行緒每個執行緒與主程式共用地址空間,一個執行緒的崩潰可能影響到整個程式的穩定性; 到達一定的執行緒數程度後,即使再增加CPU也無法提高效能,執行緒本身的排程也是一個麻煩事兒,需要消耗較多的CPU。

實驗中的知識點

1.單執行緒的也就是程式執行時,所跑的程式路徑(處理的東西)是連續順序下來的,必須前面的處理好,後面的才會執行到。

2.多執行緒處理可以同時執行多個過程。多執行緒技術使程式的響應速度更快。即在一個程式中可以同時執行多個不同的執行緒來執行不同的任務,也就是說允許單個程式建立多個並行執行的執行緒來完成各自的任務。

3.通過任務一與任務二的對比,可以感受到,多執行緒可以同步進行文字檔案的字數統計,比較方便快捷,兩個客戶端之間也不會互相影響;但單執行緒就必須統計完一個文字字數,再重新啟動客戶端才能再次統計第二個文字字數,效率較低。

4.互斥鎖主要用來保護臨界資源,什麼是臨界資源,就是有可能多個執行緒都需要訪問的資料地址,也有可能是某一段程式碼,執行這段程式碼有可能會改變多個執行緒都需要訪問的資料。

5.加入同步機制主要是為了在多執行緒程式中,如果需要對某個共享資源C進行同步訪問,什麼是同步訪問,就是A執行緒訪問過程中,B執行緒不能訪問,必須等A執行緒訪問結束後,B執行緒才能訪問

6.互斥鎖,如果用來對C進行保護,A訪問C資源的過程中,B不能訪問,A訪問結束後,B可以訪問,但不一定訪問的到,這取決於系統的排程是否給到B,如果沒有,A反而被排程到了,那麼A就有可能方法到C。
反觀同步機制,在這種情況下,如果系統沒有排程到B,A也是沒有可能訪問C的,必須等B排程到之後,A才可能重新訪問。

實驗感想

此次試驗算是比較深刻體會到了多執行緒和單執行緒的優劣之處了。多執行緒現在非常廣泛的應用與各種手機應用系統。以我所使用的iPhone來講,它的iOS允許使用者自己開闢新的執行緒,相對於主執行緒來講,這些執行緒,稱為子執行緒。可以根據需要開闢若干子執行緒。子執行緒和主執行緒都是獨立的執行單元,各自的執行互不影響,因此能夠併發執行,這樣也使手機的使用更加智慧與高效。