00001 /* 00002 Socket example program 00003 AUP2, Sec. 8.01.1 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 #include <sys/socket.h> 00023 #include <sys/un.h> 00024 /*[pgm]*/ 00025 #define SOCKETNAME "MySocket" 00026 00027 int main(void) 00028 { 00029 struct sockaddr_un sa; 00030 00031 (void)unlink(SOCKETNAME); 00032 strcpy(sa.sun_path, SOCKETNAME); 00033 sa.sun_family = AF_UNIX; 00034 if (fork() == 0) { /* client */ 00035 int fd_skt; 00036 char buf[100]; 00037 00038 ec_neg1( fd_skt = socket(AF_UNIX, SOCK_STREAM, 0) ) 00039 while (connect(fd_skt, (struct sockaddr *)&sa, sizeof(sa)) == -1) 00040 if (errno == ENOENT) { 00041 sleep(1); 00042 continue; 00043 } 00044 else 00045 EC_FAIL 00046 ec_neg1( write(fd_skt, "Hello!", 7 ) ) 00047 ec_neg1( read(fd_skt, buf, sizeof(buf)) ) 00048 printf("Client got \"%s\"\n", buf); 00049 ec_neg1( close(fd_skt) ) 00050 exit(EXIT_SUCCESS); 00051 } 00052 else { /* server */ 00053 int fd_skt, fd_client; 00054 char buf[100]; 00055 00056 ec_neg1( fd_skt = socket(AF_UNIX, SOCK_STREAM, 0) ) 00057 ec_neg1( bind(fd_skt, (struct sockaddr *)&sa, sizeof(sa)) ) 00058 ec_neg1( listen(fd_skt, SOMAXCONN) ) 00059 ec_neg1( fd_client = accept(fd_skt, NULL, 0) ) 00060 ec_neg1( read(fd_client, buf, sizeof(buf)) ) 00061 printf("Server got \"%s\"\n", buf); 00062 ec_neg1( write(fd_client, "Goodbye!", 9 ) ) 00063 ec_neg1( close(fd_skt) ) 00064 ec_neg1( close(fd_client) ) 00065 exit(EXIT_SUCCESS); 00066 } 00067 00068 EC_CLEANUP_BGN 00069 exit(EXIT_FAILURE); 00070 EC_CLEANUP_END 00071 } 00072 /*[]*/