00001 /* 00002 SOCK_DGRAM example program 00003 AUP2, Sec. 8.06.2 00004 00005 Copyright 2003 by Marc J. Rochkind. All rights reserved. 00006 May be copied only for purposes and under conditions described 00007 on the Web page www.basepath.com/aup/copyright.htm. 00008 00009 The Example Files are provided "as is," without any warranty; 00010 without even the implied warranty of merchantability or fitness 00011 for a particular purpose. The author and his publisher are not 00012 responsible for any damages, direct or incidental, resulting 00013 from the use or non-use of these Example Files. 00014 00015 The Example Files may contain defects, and some contain deliberate 00016 coding mistakes that were included for educational reasons. 00017 You are responsible for determining if and how the Example Files 00018 are to be used. 00019 00020 */ 00021 #include "defs.h" 00022 #ifdef SOLARIS 00023 #define __EXTENSIONS__ 00024 #endif 00025 #include <sys/socket.h> 00026 #undef __EXTENSIONS__ 00027 #include <sys/un.h> 00028 /*[pgm]*/ 00029 #define SOCKETNAME1 "SktOne" 00030 #define SOCKETNAME2 "SktTwo" 00031 00032 #define MSG_SIZE 100 00033 00034 int main(void) 00035 { 00036 struct sockaddr_un sa1, sa2; 00037 00038 strcpy(sa1.sun_path, SOCKETNAME1); 00039 sa1.sun_family = AF_UNIX; 00040 strcpy(sa2.sun_path, SOCKETNAME2); 00041 sa2.sun_family = AF_UNIX; 00042 (void)unlink(SOCKETNAME1); 00043 (void)unlink(SOCKETNAME2); 00044 if (fork() == 0) { /* Peer 1 */ 00045 int fd_skt; 00046 ssize_t nread; 00047 char msg[MSG_SIZE]; 00048 int i; 00049 00050 sleep(1); /* let peer 2 startup first */ 00051 ec_neg1( fd_skt = socket(AF_UNIX, SOCK_DGRAM, 0) ) 00052 ec_neg1( bind(fd_skt, (struct sockaddr *)&sa1, sizeof(sa1)) ) 00053 for (i = 1; i <= 4; i++) { 00054 snprintf(msg, sizeof(msg), "Message #%d", i); 00055 ec_neg1( sendto(fd_skt, msg, sizeof(msg), 0, 00056 (struct sockaddr *)&sa2, sizeof(sa2)) ) 00057 ec_neg1( nread = read(fd_skt, msg, sizeof(msg)) ) 00058 if (nread != sizeof(msg)) { 00059 printf("Peer 1 got short message\n"); 00060 break; 00061 } 00062 printf("Got \"%s\" back\n", msg); 00063 } 00064 ec_neg1( close(fd_skt) ) 00065 exit(EXIT_SUCCESS); 00066 } 00067 else { /* Peer 2 */ 00068 int fd_skt; 00069 ssize_t nread; 00070 char msg[MSG_SIZE]; 00071 00072 ec_neg1( fd_skt = socket(AF_UNIX, SOCK_DGRAM, 0) ) 00073 ec_neg1( bind(fd_skt, (struct sockaddr *)&sa2, sizeof(sa2)) ) 00074 while (true) { 00075 ec_neg1( nread = read(fd_skt, msg, sizeof(msg)) ) 00076 if (nread != sizeof(msg)) { 00077 printf("Peer 2 got short message\n"); 00078 break; 00079 } 00080 msg[0] = 'm'; 00081 ec_neg1( sendto(fd_skt, msg, sizeof(msg), 0, 00082 (struct sockaddr *)&sa1, sizeof(sa1)) ) 00083 } 00084 ec_neg1( close(fd_skt) ) 00085 exit(EXIT_SUCCESS); 00086 } 00087 00088 EC_CLEANUP_BGN 00089 exit(EXIT_FAILURE); 00090 EC_CLEANUP_END 00091 }