pipe.cpp

Go to the documentation of this file.
00001 /*
00002  *
00003  *  D-Bus++ - C++ bindings for D-Bus
00004  *
00005  *  Copyright (C) 2005-2007  Paolo Durante <shackan@gmail.com>
00006  *
00007  *
00008  *  This library is free software; you can redistribute it and/or
00009  *  modify it under the terms of the GNU Lesser General Public
00010  *  License as published by the Free Software Foundation; either
00011  *  version 2.1 of the License, or (at your option) any later version.
00012  *
00013  *  This library is distributed in the hope that it will be useful,
00014  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00015  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00016  *  Lesser General Public License for more details.
00017  *
00018  *  You should have received a copy of the GNU Lesser General Public
00019  *  License along with this library; if not, write to the Free Software
00020  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
00021  *
00022  */
00023 
00024 #ifdef HAVE_CONFIG_H
00025 #include <config.h>
00026 #endif
00027 
00028 /* Project */
00029 #include <dbus-c++/pipe.h>
00030 #include <dbus-c++/util.h>
00031 #include <dbus-c++/error.h>
00032 
00033 /* STD */
00034 #include <unistd.h>
00035 #include <sys/poll.h>
00036 #include <fcntl.h>
00037 #include <errno.h>
00038 #include <cassert>
00039 
00040 using namespace DBus;
00041 using namespace std;
00042 
00043 Pipe::Pipe(void(*handler)(const void *data, void *buffer, unsigned int nbyte), const void *data) :
00044   _handler(handler),
00045   _fd_write(0),
00046   _fd_read(0),
00047   _data(data)
00048 {
00049   int fd[2];
00050 
00051   if (pipe(fd) == 0)
00052   {
00053     _fd_read = fd[0];
00054     _fd_write = fd[1];
00055     fcntl(_fd_read, F_SETFL, O_NONBLOCK);
00056   }
00057   else
00058   {
00059     throw Error("PipeError:errno", toString(errno).c_str());
00060   }
00061 }
00062 
00063 void Pipe::write(const void *buffer, unsigned int nbytes)
00064 {
00065   // TODO: ignoring return of read/write generates warning; maybe relevant for eventloop work...
00066   // first write the size into the pipe...
00067   ::write(_fd_write, static_cast <const void *>(&nbytes), sizeof(nbytes));
00068 
00069   // ...then write the real data
00070   ::write(_fd_write, buffer, nbytes);
00071 }
00072 
00073 ssize_t Pipe::read(void *buffer, unsigned int &nbytes)
00074 {
00075   // TODO: ignoring return of read/write generates warning; maybe relevant for eventloop work...
00076   // first read the size from the pipe...
00077   ::read(_fd_read, &nbytes, sizeof(nbytes));
00078 
00079   //ssize_t size = 0;
00080   return ::read(_fd_read, buffer, nbytes);
00081 }
00082 
00083 void Pipe::signal()
00084 {
00085   // TODO: ignoring return of read/write generates warning; maybe relevant for eventloop work...
00086   ::write(_fd_write, '\0', 1);
00087 }