Main Page   Class Hierarchy   Alphabetical List   Compound List   File List   Compound Members   File Members  

NamedPipe.cpp

Go to the documentation of this file.
00001 #include <stdio.h>
00002 #include <stdlib.h>
00003 #include <string.h>
00004 #include <sys/types.h>
00005 #include <sys/stat.h>
00006 #include <fcntl.h>
00007 #include <unistd.h>
00008 
00009 #include "OSDependent/NamedPipe.h"
00010 
00011 void NamedPipe::buildFileName(const char* name, char* buffer) {
00012    char* tmp_dir = getenv("TMPDIR");
00013    if (tmp_dir == NULL)
00014       tmp_dir = P_tmpdir;
00015    sprintf(buffer,"%s/%s.fifo",tmp_dir,name);
00016 }
00017 
00018 NamedPipe::NamedPipe() : _pipe(-1)
00019 {
00020 }
00021 
00022 NamedPipe::~NamedPipe() {
00023    this->close();
00024 }
00025 
00026 void NamedPipe::close() {
00027    if (_pipe != -1) {
00028       ::close(_pipe);
00029       if (_is_server)
00030          unlink(_pname);
00031       _pipe = -1;
00032    }
00033 }
00034 
00035 int NamedPipe::create(const char* name, int mode, long timeout) {
00036    this->buildFileName(name,_pname);
00037    _is_server = 1;
00038 
00039    if (mkfifo(_pname,S_IFIFO|0600))
00040       return -1;
00041 
00042    int access_mode = O_RDONLY;
00043    if ((mode & NPIPE_READ) && (mode & NPIPE_WRITE))
00044       access_mode = O_RDWR;
00045    else if (mode & NPIPE_WRITE)
00046       access_mode = O_WRONLY;
00047 
00048    _pipe = open(_pname,access_mode);
00049 
00050    if (_pipe == -1) {
00051       unlink(_pname);
00052       return -1;
00053    }
00054    return 0;
00055 }
00056 
00057 int NamedPipe::connect(const char* name, int mode, long timeout) {
00058    this->buildFileName(name,_pname);
00059    _is_server = 0;
00060 
00061    int access_mode = O_RDONLY;
00062    if ((mode & NPIPE_READ) && (mode & NPIPE_WRITE))
00063       access_mode = O_RDWR;
00064    else if (mode & NPIPE_WRITE)
00065       access_mode = O_WRONLY;
00066 
00067    short tries = 0;
00068    do {
00069       _pipe = open(_pname,access_mode);
00070       tries++;
00071    }
00072    while ((_pipe==-1) && (timeout != -1) &&
00073           (usleep(timeout*100), tries <= 10));
00074 
00075    if (_pipe == -1)
00076       return -1;
00077    return 0;
00078 }
00079 
00080 long NamedPipe::write(char*buffer, long size) {
00081    return ::write(_pipe,buffer,size);
00082 }
00083 
00084 long NamedPipe::read(char*buffer, long size) {
00085    return ::read(_pipe,buffer,size);
00086 }
00087 
00088 void NamedPipe::flush() {
00089    fsync(_pipe);
00090 }
00091 

Generated on Mon Oct 7 09:33:29 2002 for Gaia by doxygen1.2.13.1 written by Dimitri van Heesch, © 1997-2001