【C語言】多進程/多線程
- 參考鏈接
- 多進程/多線程服務器
- 1. 多進程服務器
- 2. 多線程服務器
- 結語
- 參考鏈接
參考鏈接
c 中文網
菜鳥 c
多進程/多線程服務器
??多進程和多線程是常用的并發編程技術。它們都允許程序同時執行多個任務,提高了系統的資源利用率和程序的運行效率。
1. 多進程服務器
??多進程是指在操作系統中同時運行多個獨立的進程。每個進程都有自己獨立的地址空間和資源,進程間的通信通過操作系統提供的進程間通信機制進行。多進程可以充分利用多核處理器的優勢,提高系統的整體性能。然而,進程間的切換會引入較大的開銷,并且需要較高的內存開銷。
??服務器使用 fork 創建子進程來和客戶端進行通信,父進程負責取出連接請求。
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <strings.h>
#include <string.h>
#include <ctype.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <arpa/inet.h>// 信號處理函數
void waitchild(int signo)
{pid_t wpid;while (1){wpid = waitpid(-1, NULL, WNOHANG);if (wpid > 0){printf("child exit, wpid==[%d]\n", wpid);}else if (wpid == 0 || wpid == -1){break;}}
}int main()
{// 阻塞SIGCHLD信號sigset_t mask;sigemptyset(&mask);sigaddset(&mask, SIGCHLD);sigprocmask(SIG_BLOCK, &mask, NULL);int sigbol = 1;int sfd = socket(AF_INET, SOCK_STREAM, 0);// 設置端口復用int opt = 1;setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int));struct sockaddr_in soaddr;bzero(&soaddr, sizeof(soaddr));soaddr.sin_family = AF_INET;soaddr.sin_port = htons(9999);soaddr.sin_addr.s_addr = htonl(INADDR_ANY);bind(sfd, (struct sockaddr *)&soaddr, sizeof(soaddr));//監聽-listenlisten(sfd, 128);struct sockaddr_in clientsocket;socklen_t clilen;char sIP[16];while (1){clilen = sizeof(clientsocket);bzero(&clientsocket, clilen);int cfd = accept(sfd, (struct sockaddr *)&clientsocket, &clilen);/* */int pid = fork();if (pid == 0){// 子進程close(sfd);char buff[64];printf("current pid is [%d],father is [%d]\n", getpid(), getppid());while (1){memset(buff, 0x00, sizeof(buff));int n = read(cfd, buff, sizeof(buff));if (n == 0){return 0;}else if (n < 0){perror("child read error");return -1;}printf("child [%d] recv data from [%s:%d]:[%s]\n", getpid(), inet_ntop(AF_INET, &clientsocket.sin_addr.s_addr, sIP, sizeof(sIP)), ntohs(clientsocket.sin_port), buff);for (int i = 0; i < n; i++){buff[i] = toupper(buff[i]);}n = Write(cfd, buff, n);if (n <= 0){perror("child write error");return -1;}}}else if (pid > 0){// 父進程close(cfd);//假如是初次fork子進程,那么才注冊信號處理函數if (sigbol == 1){sigbol = 0;// 注冊SIGCHLD信號處理函數struct sigaction act;act.sa_handler = waitchild;act.sa_flags = 0;sigemptyset(&act.sa_mask);sigaction(SIGCHLD, &act, NULL);// 解除對SIGCHLD信號的阻塞sigprocmask(SIG_UNBLOCK, &mask, NULL);}//循環等待下一個連接請求的到來continue;}else{perror("fork error");close(sfd);return -1;}}return 0;
}
2. 多線程服務器
??多線程是指在同一個進程中同時運行多個獨立的線程。與進程不同,線程共享同一個地址空間和資源,可以通過共享內存等方式進行線程間的通信。多線程可以減少線程間的切換開銷和內存開銷,提高系統的響應速度和資源利用率。然而,多線程編程需要考慮線程安全問題,需要使用線程同步技術來保證共享資源的正確訪問。
??主線程創建子線程,用子進程和客戶端通信。
#include <arpa/inet.h>
#include <pthread.h>
#include <strings.h>
#include <string.h>
#include <ctype.h>
#include <arpa/inet.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <unistd.h>typedef struct info
{int cfd; // 若為-1表示可用, 大于0表示已被占用int idx;pthread_t thread; // 由pthread_create 返回struct sockaddr_in client; // 由accept 返回
} INFO;INFO thInfo[1024];void initThreadArr()
{for (int i = 0; i < 1024; i++){bzero(&thInfo[i],sizeof(thInfo[i]));thInfo[i].cfd = -1;}
}int findIndex()
{int i;for (i = 0; i < 1024; i++){if (thInfo[i].cfd == -1){return i;}}//if (i == 1024)//{// return -1;//}return -1;
}void *threadFunc(void *arg)
{INFO *curthread = (INFO *)arg;char sIP[16];printf("current thread id [%ld],arr index is [%d],cfd is [%d],client ip is [%s:%d]\n", pthread_self(), curthread->idx, curthread->cfd, inet_ntop(AF_INET, &curthread->client.sin_addr.s_addr, sIP, sizeof(sIP)), ntohs(curthread->client.sin_port));char buff[64];while (1){memset(buff, 0x00, sizeof(buff));int n = read(curthread->cfd, buff, sizeof(buff));if (n == 0){bzero(&thInfo[curthread->idx],sizeof(thInfo[curthread->idx]));thInfo[thInfo->idx].cfd = -1;return 0;}else if (n < 0){bzero(&thInfo[curthread->idx],sizeof(thInfo[curthread->idx]));thInfo[thInfo->idx].cfd = -1;perror("child read error");return 0;}printf("child thread [%ld] recv data from [%s:%d]:[%s]\n", pthread_self(), inet_ntop(AF_INET, &curthread->client.sin_addr.s_addr, sIP, sizeof(sIP)), ntohs(curthread->client.sin_port), buff);for (int i = 0; i < n; i++){buff[i] = toupper(buff[i]);}n = write(curthread->cfd, buff, n);if (n <= 0){bzero(&thInfo[curthread->idx],sizeof(thInfo[curthread->idx]));thInfo[thInfo->idx].cfd = -1;perror("child write error");return 0;}}
}int main()
{initThreadArr();int sfd = socket(AF_INET, SOCK_STREAM, 0);// 設置端口復用int opt = 1;setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int));struct sockaddr_in soaddr;bzero(&soaddr, sizeof(soaddr));soaddr.sin_family = AF_INET;soaddr.sin_port = htons(9999);soaddr.sin_addr.s_addr = htonl(INADDR_ANY);bind(sfd, (struct sockaddr *)&soaddr, sizeof(soaddr));// 監聽-listenlisten(sfd, 128);struct sockaddr_in clientsocket;socklen_t clilen;int cfd;int index;int ret;while (1){index = -1;clilen = sizeof(clientsocket);bzero(&clientsocket, clilen);cfd = accept(sfd, (struct sockaddr *)&clientsocket, &clilen);// 從線程數組中找一個可以用的index = findIndex();thInfo[index].idx = index;thInfo[index].client = clientsocket;thInfo[index].cfd = cfd;// 創建線程ret = pthread_create(&thInfo[index].thread, NULL, threadFunc, &thInfo[index]);if (ret != 0){printf("create thread error:[%s]\n", strerror(ret));exit(-1);}// 設置子線程為分離屬性pthread_detach(thInfo[index].thread);}Close(sfd);return 0;
}
結語
??多進程和多線程的選擇取決于具體的應用場景。如果任務之間需要較高的隔離度,或者需要充分利用多核處理器的優勢,可以選擇多進程。如果任務之間需要較低的切換開銷和內存開銷,或者需要提高系統的響應速度和資源利用率,可以選擇多線程。
參考鏈接
c 中文網
菜鳥 c