aboutsummaryrefslogtreecommitdiff
path: root/src/fifo.cpp
blob: f34bb9199963f429c4e38db819bc1b97e47e202b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/*
 * Copyright (C) 2007-2008 Xagasoft, All rights reserved.
 *
 * This file is part of the libbu++ library and is released under the
 * terms of the license contained in the file LICENSE.
 */

#include "fifo.h"
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

namespace Bu { subExceptionDef( FifoException ) }

Bu::Fifo::Fifo( const Bu::FString &sName, int iFlags, mode_t mAcc ) :
	iFlags( iFlags ),
	iIn( -1 ),
	iOut( -1 )
{
	if( iFlags&Create )
	{
		if( mkfifo( sName.getStr(), mAcc ) )
		{
			throw FifoException("Error creating fifo: %s\n", strerror( errno ) );
		}
	}
	if( iFlags&Read )
	{
		iIn = ::open(
			sName.getStr(),
			O_RDONLY|((iFlags&NonBlock)?O_NONBLOCK:0)
			);
	}
	if( iFlags&Write )
	{
		iOut = ::open(
			sName.getStr(),
			O_WRONLY
			);
	}
}

Bu::Fifo::~Fifo()
{
	close();
}

void Bu::Fifo::close()
{
	if( iIn > -1 )
	{
		::close( iIn );
		iIn = -1;
	}
	if( iOut > -1 )
	{
		::close( iOut );
		iOut = -1;
	}
}

size_t Bu::Fifo::read( void *pBuf, size_t nBytes )
{
	if( iIn < 0 )
		throw FifoException("Fifo not open for reading.");

	return TEMP_FAILURE_RETRY( ::read( iIn, pBuf, nBytes ) );
}

size_t Bu::Fifo::write( const void *pBuf, size_t nBytes )
{
	if( iOut < 0 )
		throw FifoException("Fifo not open for writing.");

	return TEMP_FAILURE_RETRY( ::write( iOut, pBuf, nBytes ) );
}

long Bu::Fifo::tell()
{
	return -1;
}

void Bu::Fifo::seek( long )
{
}

void Bu::Fifo::setPos( long )
{
}

void Bu::Fifo::setPosEnd( long )
{
}

bool Bu::Fifo::isEos()
{
	return false;
}

bool Bu::Fifo::canRead()
{
	return (iIn>-1);
}

bool Bu::Fifo::canWrite()
{
	return (iOut>-1);
}

bool Bu::Fifo::isReadable()
{
	return (iIn>-1);
}

bool Bu::Fifo::isWritable()
{
	return (iOut>-1);
}

bool Bu::Fifo::isSeekable()
{
	return false;
}

bool Bu::Fifo::isBlocking()
{
	return ((fcntl( iIn, F_GETFL, 0 )&O_NONBLOCK) == O_NONBLOCK);
}

void Bu::Fifo::setBlocking( bool bBlocking )
{
	if( bBlocking )
		fcntl( iIn, F_SETFL, fcntl( iIn, F_GETFL, 0 )&(~O_NONBLOCK) );
	else
		fcntl( iIn, F_SETFL, fcntl( iIn, F_GETFL, 0 )|O_NONBLOCK );
}

void Bu::Fifo::flush()
{
}

bool Bu::Fifo::isOpen()
{
	return (iIn > -1) || (iOut > -1);
}