#include #include #include #include #include #include #include #include // $ g++ --std=gnu++17 af_unix.cpp const char* const path = "address"; const int count = 1000; const int size = BUFSIZ * 2; int client() { const int fd = socket( AF_UNIX, SOCK_DGRAM, 0); if( fd == -1) { perror( "socket error"); return -1; } struct sockaddr_un address{}; strcpy( address.sun_path, path); address.sun_family = AF_UNIX; char buffer[size] = {}; for( int idx = 0; idx < count; ++idx) { memcpy( buffer, &idx, sizeof idx); const ssize_t result = sendto( fd, buffer, size, 0, (struct sockaddr*)&address, sizeof address); if( result == -1 || result != size) { perror( "sendto error"); return -1; } } close( fd); return 0; } int server() { const int fd = socket( AF_UNIX, SOCK_DGRAM, 0); if( fd == -1) { perror( "socket error"); return -1; } struct sockaddr_un address{}; strcpy( address.sun_path, path); address.sun_family = AF_UNIX; const int result = bind( fd, (struct sockaddr*)&address, sizeof address); if( result == -1) { perror( "bind error"); return -1; } return fd; } int main( int argc, char* argv[]) { const int fd = server( ); if( fd != -1) { fprintf( stdout, "%d\tnumber of packages\n", count); fprintf( stdout, "%d\tbytes per package\n", size); std::thread{ [&](){client( );}}.detach(); std::this_thread::sleep_for( std::chrono::microseconds( 500)); char buffer[size] = {}; for( int idx = 0; idx < count; ++idx) { const ssize_t result = recv( fd, buffer, size, 0); if( result == -1 || result != size) { perror("recv error"); unlink( path); return -1; } int index = 0; memcpy( &index, buffer, sizeof idx); if( index != idx) { fprintf( stderr, "expected %d but got %d\n", idx, index); unlink( path); return -1; } } close( fd); unlink( path); } return 0; }