[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: fork() and socketpair()



Francesco Orsenigo wrote:
> My program forks into two separate processes, and i must connect them with
> a pipe wich i must be able to use with send() and recv().
> socketpair is perfect (i socketpair() and then fork()) but it seems not
> very portable.
> The alternative would be fork() and then link the two processes with
> standard socket()/connect()/listen() calls.
>
> I thought about using pipe(), but it is not full-duplex and i don't know if
> it is safe to use with send() and recv().
>
> Thanx,
> Francesco Orsenigo,
> Xarvh Projext
> http://freeweb.lombardiacom.it/xarvh/

Hello,

I do not know what portability consideration you have in mind, 
but under Linux a call to socketpair is perfect:
   int  sv[2] ;
   int  r = socketpair( PF_UNIX, SOCK_STREAM, AF_LOCAL, sv) ;
If socketpair does not exist you could use a call to 
  sv[0] = socket( PF_UNIX,  SOCK_STREAM, AF_LOCAL)
  sv[1] = ...
and then call connect and listen as you have already said.
A call to socketpair() has the same portability issues than a call to socket
on Unix (is not valid for Win32).

Joerg
Seebohn
http://www.s.netic.de/jseebohn


PS - The following is a test program I have used under Linux.

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <iostream>
#include <errno.h>
#include <string.h>
#include <fcntl.h>


int main(int argc, char* argv[])
{

   int  sv[2] ;
   int  r = socketpair( PF_UNIX, SOCK_STREAM, AF_LOCAL, sv) ;
   char buffer[100] ;

   if (r)
   {
      std::cout << "socketpair error: " << strerror(errno) << std::endl ;
      exit(1) ;
   }

   if (fork())
   {
      int s = sv[0] ;
      close( sv[1] ) ;
      /* parent */
      int size = recv( s, buffer, sizeof(buffer), 0) ;
      if (size < 0) std::cout << "recv error: " << strerror(errno) << 
std::endl ;
      std::cout << "size: " << size << " msg: '" << buffer << "'" << 
std::endl ;
      send( s, "hello child", 12, 0) ;
   }
   else
   {
      int s = sv[1] ;
      close(sv[0]) ;
      /* child */
      send( s, "hello parent", 13, 0) ;
      int size = recv( s, buffer, sizeof(buffer), 0) ;
      if (size < 0) std::cout << "recv error: " << strerror(errno) << 
std::endl ;
      std::cout << "size: " << size << " msg: '" << buffer << "'" <<   
std::endl ;

   }

   return 0 ;
}