linux 本地通訊例項 AF UNIX

2021-06-27 18:09:16 字數 2711 閱讀 4610

程式說明:

程式裡包含服務端和客戶端兩個程式,它們之間使用 af_unix 實現本機資料流通訊。使用 af_unix 域實際上是使用本地 socket 檔案來通訊。

伺服器端**:

#include

#include

#include

#include

#include

#include

int 

main (

intargc

,char

*argv

)printf (

"the server is waiting for client data...

\n ");

for( i=0

,ch_send

='1'; 

i<

5;  i++,

ch_send

++) 

printf (

"the character receiver from client is %c

\n "

,ch_recv);

sleep (

1);if

(( bytes

=write (

client_sockfd,&

ch_send

,1)) 

==-1)  }

close (

client_sockfd);

unlink (

"server socket"); }

客戶端**:

#include

#include

#include

#include

#include

#include

int 

main (

intargc

,char

*argv

)address

.sun_family

=af_unix;

strcpy (

address

.sun_path

,"server_socket");

len=sizeof

( address);

/*向伺服器傳送連線請求*/

result

=connect (

sockfd

, ( struct

sockaddr

*) &

address

,len);

if( result==-

1) 

for (

i=0,

ch_send

='a'; 

i<

5;  i++,

ch_send

++) 

sleep (

2);    

/*休息二秒鐘再發一次*/

if(( bytes

=read (

sockfd,&

ch_recv

,1)) 

==-1) 

printf (

"receive from server data is %c

\n "

,ch_recv); }

close (

sockfd);

return

( 0); }

./sock_local_server 

server is waiting for client connect...

./sock_local_client 

ensure the server is up

connect: connection refused

提示伺服器沒有準備好,連線被拒絕,從而直接退出程式。

如果伺服器和客戶端依次執行,可以在兩邊看到輸出:

伺服器端:

./sock_local_server 

server is waiting for client connect...

the server is waiting for client data...

the character receiver from client is a

the character receiver from client is b

the character receiver from client is c

the character receiver from client is d

the character receiver from client is e

客戶端:

./sock_local_client 

receive from server data is 1

receive from server data is 2

receive from server data is 3

receive from server data is 4

receive from server data is 5

linux 本地通訊 socketpair 的使用

linux 本地通訊 socketpair 的使用linux 下本地通訊的方式有多種,此次介紹socketpair的使用。函式原型 name socketpair create a pair of connected sockets synopsis include int socketpair i...

Linux命名管道通訊例項

理解 suck 端簡單實現 include include include include include 讀取方式巨集定義 include 使用者許可權巨集定義 includeint main 如果鍵盤有輸入 if fd isset fileno stdin read fd close rfd c...

IIC 通訊例項

iic 標籤 1 標準速率 100kbit s 快速 400kbit s 高速 4mbit s 2 2線通訊協議 3 起始與停止 scl高時,sda由 高 低 變化,起始訊號 sda由 低 高 變化,停止訊號 4 空閒狀態 sda和scl都處於高電平狀態 5 資料傳輸與應答 資料必須是8位,且高位在...