diff --git a/src/backend/storage/ipc/shm_mq.c b/src/backend/storage/ipc/shm_mq.c
index 7d1c9cd..5ed0cef 100644
--- a/src/backend/storage/ipc/shm_mq.c
+++ b/src/backend/storage/ipc/shm_mq.c
@@ -366,9 +366,12 @@ shm_mq_sendv(shm_mq_handle *mqh, shm_mq_iovec *iov, int iovcnt, bool nowait)
 		res = shm_mq_send_bytes(mqh, sizeof(Size) - mqh->mqh_partial_bytes,
 								((char *) &nbytes) +mqh->mqh_partial_bytes,
 								nowait, &bytes_written);
-		mqh->mqh_partial_bytes += bytes_written;
-		if (res != SHM_MQ_SUCCESS)
+		if (res == SHM_MQ_DETACHED)
+		{
+			mqh->mqh_partial_bytes = 0;
 			return res;
+		}
+		mqh->mqh_partial_bytes += bytes_written;
 
 		if (mqh->mqh_partial_bytes >= sizeof(Size))
 		{
@@ -378,6 +381,9 @@ shm_mq_sendv(shm_mq_handle *mqh, shm_mq_iovec *iov, int iovcnt, bool nowait)
 			mqh->mqh_length_word_complete = true;
 		}
 
+		if (res != SHM_MQ_SUCCESS)
+			return res;
+
 		/* Length word can't be split unless bigger than required alignment. */
 		Assert(mqh->mqh_length_word_complete || sizeof(Size) > MAXIMUM_ALIGNOF);
 	}
@@ -434,6 +440,11 @@ shm_mq_sendv(shm_mq_handle *mqh, shm_mq_iovec *iov, int iovcnt, bool nowait)
 			}
 			res = shm_mq_send_bytes(mqh, j, tmpbuf, nowait, &bytes_written);
 			mqh->mqh_partial_bytes += bytes_written;
+			if (res == SHM_MQ_DETACHED)
+			{
+				mqh->mqh_partial_bytes = 0;
+				return res;
+			}
 			if (res != SHM_MQ_SUCCESS)
 				return res;
 			continue;
@@ -449,6 +460,11 @@ shm_mq_sendv(shm_mq_handle *mqh, shm_mq_iovec *iov, int iovcnt, bool nowait)
 			chunksize = MAXALIGN_DOWN(chunksize);
 		res = shm_mq_send_bytes(mqh, chunksize, &iov[which_iov].data[offset],
 								nowait, &bytes_written);
+		if (res == SHM_MQ_DETACHED)
+		{
+			mqh->mqh_partial_bytes = 0;
+			return res;
+		}
 		mqh->mqh_partial_bytes += bytes_written;
 		offset += bytes_written;
 		if (res != SHM_MQ_SUCCESS)
