linux 进程间通讯 第一步
主要是参考 http://beej.us/guide/bgipc/ 写出来的
国人写的基本全是转载 不是代码残疾 就是根本看不懂的……广告
整理下 g++编译
Server.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | #include <iostream> using namespace std; #include <sys/socket.h> #include <sys/un.h> const int MAX_RECV = 500; int main(int argc, char ** argv){ sockaddr_un server; // sockaddr_un 表示使用socket文件 参考 sockaddr_in server.sun_family = AF_UNIX; strcpy(server.sun_path, "test.socket"); unlink(server.sun_path); // 绑定之前 清理掉 int s = socket(AF_UNIX, SOCK_STREAM, 0); bind(s , (sockaddr *) &server, sizeof(server)); listen(s, 5); for(;;){ cout<<"Wating"<<endl; sockaddr_un client; socklen_t client_len = sizeof(client); int c = accept(s, (sockaddr *) &client, &client_len); cout<<"Connected " <<endl; char buf[MAX_RECV]; int len; while( (len = recv(c, &buf, MAX_RECV, 0)) >0 ){ // 处理buf cout <<"Client Says:" << buf <<endl; send(c, buf, len, 0); //写入client } } return 0; } |
client.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #include <iostream> using namespace std; #include <sys/socket.h> #include <sys/un.h> const int MAX_RECV = 500; int main(int argc, char ** argv){ sockaddr_un server; // sockaddr_un 表示使用socket文件 参考 sockaddr_in server.sun_family = AF_UNIX; strcpy(server.sun_path, "test.socket"); int s = socket(AF_UNIX, SOCK_STREAM, 0); connect(s, (sockaddr *) &server, sizeof(server)); char str[MAX_RECV]; char buf[MAX_RECV]; while(cin>>str){ send(s, str, sizeof(str), 0); if( recv(s, &buf, MAX_RECV, 0) >0 ){ // 处理buf cout << "Server Say:" << buf <<endl; } } return 0; } |
Makefile
1 2 3 4 5 6 7 | all: server client server: server.cpp g++ -o server server.cpp client: client.cpp g++ -o client client.cpp |
