linux多程序併發伺服器

2021-10-23 15:24:53 字數 2472 閱讀 8600

多程序併發伺服器,多執行緒版

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

//程序**函式

void

recyle

(int num)

}int

main

(int argc,

char

const

*ar**)

struct sockaddr_in serv_addr;

socklen_t serv_len =

sizeof

(serv_addr)

;int port =

atoi

(ar**[1]

);//建立套接字

int lfd =

socket

(af_inet,sock_stream,0)

;//初始化伺服器 sockaddr_in

memset

(&serv_addr,

0,serv_len)

; serv_addr.sin_family = af_inet;

//位址族

serv_addr.sin_addr.s_addr =

htonl

(inaddr_any)

;//監聽本機所有的ip

serv_addr.sin_port =

htons

(port)

;//設定埠

//繫結ip和埠

bind

(lfd,

(struct sockaddr*

)&serv_addr,serv_len)

;//設定同時監聽的最大個數

listen

(lfd,36)

;printf

("start accept ......\n");

//使用訊號**子程序pcb

struct sigaction act;

act.sa_handler = recyle;

act.sa_flags =0;

sigemptyset

(&act.sa_mask)

;sigaction

(sigchld,

&act,

null);

struct sockaddr_in client_addr;

socklen_t cli_len =

sizeof

(client_addr)

;while(1

)printf

("connect sucessful\n");

//建立子程序

pid_t pid =

fork()

;if(pid ==0)

else

if(len ==0)

else

}//乾掉子程序

return0;

}else

if(pid>0)

}close

(lfd)

;return0;

}

$ gcc process_server.c -o server

$ ./server 9876

start accept ......

connect sucessful

client ip: 127.0.0.1, port: 33720

recv buf: 001

client ip: 127.0.0.1, port: 33720

connect sucessful

client ip: 127.0.0.1, port: 33726

recv buf: 002

client ip: 127.0.0.1, port: 33726

recv buf: nihao

client ip: 127.0.0.1, port: 33720

recv buf: mmm

client ip: 127.0.0.1, port: 33726

客戶端斷開了連線

child died , pid = 17949

客戶端斷開了連線

child died , pid = 17657

...

由於採用while迴圈,客戶端斷開後,沒有報錯

$ nc 127.1 9876

001001

nihao

nihao

^c$

$ nc 127.1 9876

002002

mmmmmm

^c$

Linux 併發伺服器程式設計(多程序)

在linux中通過流式套接字程式設計 tcp 實現乙個併發伺服器的訪問回顯,適合剛學完linux套接字程式設計的朋友進行鞏固訓練 具體功能 include include include include include include include include include include ...

Linux 併發伺服器程式設計(多程序)

在linux中通過流式套接字程式設計 tcp 實現乙個併發伺服器的訪問回顯,適合剛學完linux套接字程式設計的朋友進行鞏固訓練 具體功能 include include include include include include include include include include ...

併發伺服器 多程序實現

通過簡單的socket可以實現一對一的c s通訊,當多個客戶端同時進行伺服器訪問,那麼伺服器只能按序的一一進行處理,除了第乙個客戶端,其餘客戶端都會陷入等待。並且這樣的程式只能實現半雙工通訊 資料能雙向傳輸,但同一時刻只能單向傳遞,通過切換傳輸方向實現雙工 而且實現方式繁瑣,功能拘束,實用價值很低。...