Linux中利用子程序實現多個客戶端和伺服器端通訊

2021-08-13 08:55:31 字數 1005 閱讀 5323

我在前面一篇部落格中已經講過了客戶端和伺服器端通訊的流程和所需要用到的系統呼叫

那麼,這篇部落格我就利用子程序實現多個客戶端和伺服器端通訊

**實現:

ser.c

#include #include #include #include #include #include #include #include int main()

printf("accept: c = %d,ip:%s,port:%d\n",c,inet_ntoa(caddr.sin_addr),ntohs(caddr.sin_port));

pid_t pid = fork();

assert(pid != -1);

if(pid == 0)

;

int len = recv(c,buff,128,0);

if(len <= 0)

printf("read(%d) = %s",c,buff);

send(c,"ok",2,0);

}close(c);

} }}

cli.c

#include #include #include #include #include #include #include #include int main()

; fgets(buff,128,stdin);

if(strncmp(buff,"end",3) == 0)

send(sockfd,buff,strlen(buff),0);

memset(buff,0,128);

recv(sockfd,buff,127,0);

printf("buff = %s\n",buff);

} close(sockfd);

}

執行結果:

Linux中父程序和子程序關係講解

先上 include include intmain else if ret 0 else return0 pid t getpid void 誰呼叫獲取誰的程序pid pid t getppid void 誰呼叫獲取誰的父程序pid 整體流程如下 輸入ps aux grep test檢視程序控制資...

linux中建立多個子程序的方法

今天,師兄問我乙個問題說 小濤啊,建立兩個程序太簡單了,怎麼建立多個程序呢?我說那還不容易,看下邊 省略必要標頭檔案 int main if pid 0 0 printf this is parent d,child is d n getppid getpid else wait 5 return ...

linux利用shell實現守護程序的指令碼

在遊戲開發領域,伺服器宕機那是家常便飯。本文簡單介紹如何利用linux的shell指令碼實現簡單的守護程序。bin sh 新增本地執行路徑 export ld library path while true do 啟動乙個迴圈,定時檢查程序是否存在 server ps aux grep center...