Skip to content

Commit dd26871

Browse files
committed
fix bug of writing after disconnected. sendInLoop() could be queued and called after handleClose().
1 parent 87b372a commit dd26871

1 file changed

Lines changed: 14 additions & 3 deletions

File tree

muduo/net/TcpConnection.cc

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,12 @@ void TcpConnection::sendInLoop(const void* data, size_t len)
138138
loop_->assertInLoopThread();
139139
ssize_t nwrote = 0;
140140
size_t remaining = len;
141+
bool error = false;
142+
if (state_ != kConnected)
143+
{
144+
LOG_WARN << "state = " << state_ << ", give up writing";
145+
return;
146+
}
141147
// if no thing in output queue, try writing directly
142148
if (!channel_->isWriting() && outputBuffer_.readableBytes() == 0)
143149
{
@@ -156,12 +162,16 @@ void TcpConnection::sendInLoop(const void* data, size_t len)
156162
if (errno != EWOULDBLOCK)
157163
{
158164
LOG_SYSERR << "TcpConnection::sendInLoop";
165+
if (errno == EPIPE) // FIXME: any others?
166+
{
167+
error = true;
168+
}
159169
}
160170
}
161171
}
162172

163173
assert(remaining <= len);
164-
if (remaining > 0)
174+
if (!error && remaining > 0)
165175
{
166176
LOG_TRACE << "I am going to write more data";
167177
size_t oldLen = outputBuffer_.readableBytes();
@@ -289,14 +299,15 @@ void TcpConnection::handleWrite()
289299
}
290300
else
291301
{
292-
LOG_TRACE << "Connection is down, no more writing";
302+
LOG_TRACE << "Connection fd = " << channel_->fd()
303+
<< " is down, no more writing";
293304
}
294305
}
295306

296307
void TcpConnection::handleClose()
297308
{
298309
loop_->assertInLoopThread();
299-
LOG_TRACE << "TcpConnection::handleClose state = " << state_;
310+
LOG_TRACE << "fd = " << channel_->fd() << " state = " << state_;
300311
assert(state_ == kConnected || state_ == kDisconnecting);
301312
// we don't close fd, leave it to dtor, so we can find leaks easily.
302313
setState(kDisconnected);

0 commit comments

Comments
 (0)