socketpair.c
00001 #include <stdio.h>
00002 #include <stdlib.h>
00003 #include <unistd.h>
00004 #include <sys/socket.h>
00005 #include <string.h>
00006
00007 #define REQUETE "Luc, je suis ton père!"
00008 #define REPONSE "Nonnnnnnnnn !"
00009
00010 void error(char * msg);
00011 int main()
00012 {
00013 int sockfd[2];
00014 char buf[1024];
00015 size_t answer_size = strlen(REPONSE) + 1;
00016 size_t request_size = strlen(REQUETE) + 1;
00017
00018 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockfd ) < 0) error("[socketpair]");
00019 pid_t childpid = fork();
00020 if ( childpid < 0 ) error("[fork]");
00021
00022 if (childpid) {
00023
00024 close(sockfd[0]);
00025
00026 ssize_t n = recv(sockfd[1], buf, sizeof(buf)-1, 0);
00027 if (n < 0) error("[recv]");
00028 buf[sizeof(buf)-1] = '\0';
00029 printf("[processus père] reception : <%s>\n",buf);
00030
00031 n = send(sockfd[1], REPONSE, answer_size, 0);
00032 if (n != answer_size) error("[send]");
00033 printf("[processus père] emission : <%s>\n",REPONSE);
00034 close(sockfd[1]);
00035 } else {
00036
00037 close(sockfd[1]);
00038
00039 ssize_t n = send(sockfd[0], REQUETE, request_size, 0);
00040 if (n != request_size) error("[send]");
00041 printf("[processus fils] emission : <%s>\n",REQUETE);
00042
00043 n = recv(sockfd[0], buf, sizeof(buf)-1, 0);
00044 if (n < 0) perror("[recv]");
00045 buf[sizeof(buf)-1] = '\0';
00046 printf("[processus fils] reception : <%s>\n",buf);
00047 close(sockfd[0]);
00048 }
00049 return EXIT_SUCCESS;
00050 }
00051
00052 void error(char * msg) {
00053 perror(msg);
00054 exit(EXIT_FAILURE);
00055 }