Qt 4.8
Public Types | Signals | Public Functions | Protected Functions | Private Functions | Properties | List of all members
QUnixSocket Class Reference

The QUnixSocket class provides a Unix domain socket. More...

#include <qunixsocket_p.h>

Inheritance diagram for QUnixSocket:
QIODevice QObject

Public Types

enum  SocketError {
  NoError, InvalidPath, ResourceError, NonexistentPath,
  ConnectionRefused, UnknownError, ReadFailure, WriteFailure
}
 The SocketError enumeration represents the various errors that can occur on a Unix domain socket. More...
 
enum  SocketState {
  UnconnectedState = QAbstractSocket::UnconnectedState, HostLookupState = QAbstractSocket::HostLookupState, ConnectingState = QAbstractSocket::ConnectingState, ConnectedState = QAbstractSocket::ConnectedState,
  BoundState = QAbstractSocket::BoundState, ClosingState = QAbstractSocket::ClosingState, ListeningState = QAbstractSocket::ListeningState
}
 The SocketState enumeration represents the connection state of a QUnixSocket instance. More...
 
- Public Types inherited from QIODevice
enum  OpenModeFlag {
  NotOpen = 0x0000, ReadOnly = 0x0001, WriteOnly = 0x0002, ReadWrite = ReadOnly | WriteOnly,
  Append = 0x0004, Truncate = 0x0008, Text = 0x0010, Unbuffered = 0x0020
}
 This enum is used with open() to describe the mode in which a device is opened. More...
 

Signals

void stateChanged (SocketState socketState)
 This signal is emitted each time the socket changes connection state. More...
 
- Signals inherited from QIODevice
void aboutToClose ()
 This signal is emitted when the device is about to close. More...
 
void bytesWritten (qint64 bytes)
 This signal is emitted every time a payload of data has been written to the device. More...
 
void readChannelFinished ()
 This signal is emitted when the input (reading) stream is closed in this device. More...
 
void readyRead ()
 This signal is emitted once every time new data is available for reading from the device. More...
 
- Signals inherited from QObject
void destroyed (QObject *=0)
 This signal is emitted immediately before the object obj is destroyed, and can not be blocked. More...
 

Public Functions

void abort ()
 Abort the connection. More...
 
QByteArray address () const
 Returns the Unix path address passed to QUnixSocket::connect() . More...
 
qint64 bytesAvailable () const
 Returns the number of bytes available for immediate retrieval through a call to QUnixSocket::read() . More...
 
qint64 bytesToWrite () const
 Returns the number of enqueued bytes still to be written to the socket. More...
 
bool canReadLine () const
 
void close ()
 Close the connection. More...
 
bool connect (const QByteArray &path)
 Attempt to connect to path. More...
 
SocketError error () const
 Returns the last error to have occurred on this object. More...
 
bool flush ()
 This function writes as much as possible from the internal write buffer to the underlying socket, without blocking. More...
 
virtual bool isSequential () const
 
 QUnixSocket (QObject *=0)
 Construct a QUnixSocket instance, with parent. More...
 
 QUnixSocket (qint64, qint64, QObject *=0)
 Construct a QUnixSocket instance, with parent. More...
 
qint64 read (char *data, qint64 maxSize)
 
QByteArray read (qint64 maxSize)
 
QUnixSocketMessage read ()
 Return the next available message, or an empty message if none is available. More...
 
qint64 readBufferSize () const
 Returns the size of the read buffer in bytes. More...
 
qint64 rightsBufferSize () const
 Returns the size of the rights buffer in rights entries. More...
 
void setReadBufferSize (qint64 size)
 Sets the size of the socket's read buffer in bytes. More...
 
void setRightsBufferSize (qint64 size)
 Sets the size of the socket's rights buffer in rights entries. More...
 
bool setSocketDescriptor (int socketDescriptor)
 Sets the socket descriptor to use to socketDescriptor, bypassing QUnixSocket's connection infrastructure, and return true on success and false on failure. More...
 
int socketDescriptor () const
 Returns the socket descriptor currently in use. More...
 
SocketState state () const
 Returns the connection state of this instance. More...
 
virtual bool waitForBytesWritten (int msec=300)
 For buffered devices, this function waits until a payload of buffered written data has been written to the device and the bytesWritten() signal has been emitted, or until msecs milliseconds have passed. More...
 
virtual bool waitForReadyRead (int msec=300)
 
qint64 write (const char *data, qint64 maxSize)
 
qint64 write (const QByteArray &byteArray)
 
qint64 write (const QUnixSocketMessage &)
 Writes socketdata to the socket. More...
 
virtual ~QUnixSocket ()
 Destroys the QUnixSocket instance. More...
 
- Public Functions inherited from QIODevice
virtual bool atEnd () const
 Returns true if the current read and write position is at the end of the device (i.e. More...
 
QString errorString () const
 Returns a human-readable description of the last device error that occurred. More...
 
bool getChar (char *c)
 Reads one character from the device and stores it in c. More...
 
bool isOpen () const
 Returns true if the device is open; otherwise returns false. More...
 
bool isReadable () const
 Returns true if data can be read from the device; otherwise returns false. More...
 
bool isTextModeEnabled () const
 Returns true if the Text flag is enabled; otherwise returns false. More...
 
bool isWritable () const
 Returns true if data can be written to the device; otherwise returns false. More...
 
virtual bool open (OpenMode mode)
 Opens the device and sets its OpenMode to mode. More...
 
OpenMode openMode () const
 Returns the mode in which the device has been opened; i.e. More...
 
qint64 peek (char *data, qint64 maxlen)
 Reads at most maxSize bytes from the device into data, without side effects (i. More...
 
QByteArray peek (qint64 maxlen)
 Peeks at most maxSize bytes from the device, returning the data peeked as a QByteArray. More...
 
virtual qint64 pos () const
 For random-access devices, this function returns the position that data is written to or read from. More...
 
bool putChar (char c)
 Writes the character c to the device. More...
 
 QIODevice ()
 Constructs a QIODevice object. More...
 
 QIODevice (QObject *parent)
 Constructs a QIODevice object with the given parent. More...
 
qint64 read (char *data, qint64 maxlen)
 Reads at most maxSize bytes from the device into data, and returns the number of bytes read. More...
 
QByteArray read (qint64 maxlen)
 Reads at most maxSize bytes from the device, and returns the data read as a QByteArray. More...
 
QByteArray readAll ()
 Reads all available data from the device, and returns it as a QByteArray. More...
 
qint64 readLine (char *data, qint64 maxlen)
 This function reads a line of ASCII characters from the device, up to a maximum of maxSize - 1 bytes, stores the characters in data, and returns the number of bytes read. More...
 
QByteArray readLine (qint64 maxlen=0)
 Reads a line from the device, but no more than maxSize characters, and returns the result as a QByteArray. More...
 
virtual bool reset ()
 Seeks to the start of input for random-access devices. More...
 
virtual bool seek (qint64 pos)
 For random-access devices, this function sets the current position to pos, returning true on success, or false if an error occurred. More...
 
void setTextModeEnabled (bool enabled)
 If enabled is true, this function sets the Text flag on the device; otherwise the Text flag is removed. More...
 
virtual qint64 size () const
 For open random-access devices, this function returns the size of the device. More...
 
void ungetChar (char c)
 Puts the character c back into the device, and decrements the current position unless the position is 0. More...
 
qint64 write (const char *data, qint64 len)
 Writes at most maxSize bytes of data from data to the device. More...
 
qint64 write (const char *data)
 Writes data from a zero-terminated string of 8-bit characters to the device. More...
 
qint64 write (const QByteArray &data)
 Writes the content of byteArray to the device. More...
 
virtual ~QIODevice ()
 The destructor is virtual, and QIODevice is an abstract base class. More...
 
- Public Functions inherited from QObject
bool blockSignals (bool b)
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). More...
 
const QObjectListchildren () const
 Returns a list of child objects. More...
 
bool connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=0, const QObject *receiver=0, const char *member=0)
 
bool disconnect (const QObject *receiver, const char *member=0)
 
void dumpObjectInfo ()
 Dumps information about signal connections, etc. More...
 
void dumpObjectTree ()
 Dumps a tree of children to the debug output. More...
 
QList< QByteArraydynamicPropertyNames () const
 Returns the names of all properties that were dynamically added to the object using setProperty(). More...
 
virtual bool event (QEvent *)
 This virtual function receives events to an object and should return true if the event e was recognized and processed. More...
 
virtual bool eventFilter (QObject *, QEvent *)
 Filters events if this object has been installed as an event filter for the watched object. More...
 
template<typename T >
findChild (const QString &aName=QString()) const
 Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. More...
 
template<typename T >
QList< T > findChildren (const QString &aName=QString()) const
 Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. More...
 
template<typename T >
QList< T > findChildren (const QRegExp &re) const
 
bool inherits (const char *classname) const
 Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false. More...
 
void installEventFilter (QObject *)
 Installs an event filter filterObj on this object. More...
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false. More...
 
void killTimer (int id)
 Kills the timer with timer identifier, id. More...
 
virtual const QMetaObjectmetaObject () const
 Returns a pointer to the meta-object of this object. More...
 
void moveToThread (QThread *thread)
 Changes the thread affinity for this object and its children. More...
 
QString objectName () const
 
QObjectparent () const
 Returns a pointer to the parent object. More...
 
QVariant property (const char *name) const
 Returns the value of the object's name property. More...
 
Q_INVOKABLE QObject (QObject *parent=0)
 Constructs an object with parent object parent. More...
 
void removeEventFilter (QObject *)
 Removes an event filter object obj from this object. More...
 
void setObjectName (const QString &name)
 
void setParent (QObject *)
 Makes the object a child of parent. More...
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value. More...
 
void setUserData (uint id, QObjectUserData *data)
 
bool signalsBlocked () const
 Returns true if signals are blocked; otherwise returns false. More...
 
int startTimer (int interval)
 Starts a timer and returns a timer identifier, or returns zero if it could not start a timer. More...
 
QThreadthread () const
 Returns the thread in which the object lives. More...
 
QObjectUserDatauserData (uint id) const
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects. More...
 

Protected Functions

virtual qint64 readData (char *data, qint64 maxSize)
 
virtual qint64 writeData (const char *data, qint64 maxSize)
 
- Protected Functions inherited from QIODevice
 QIODevice (QIODevicePrivate &dd, QObject *parent=0)
 
virtual qint64 readLineData (char *data, qint64 maxlen)
 Reads up to maxSize characters into data and returns the number of characters read. More...
 
void setErrorString (const QString &errorString)
 Sets the human readable description of the last device error that occurred to str. More...
 
void setOpenMode (OpenMode openMode)
 Sets the OpenMode of the device to openMode. More...
 
- Protected Functions inherited from QObject
virtual void childEvent (QChildEvent *)
 This event handler can be reimplemented in a subclass to receive child events. More...
 
virtual void connectNotify (const char *signal)
 This virtual function is called when something has been connected to signal in this object. More...
 
virtual void customEvent (QEvent *)
 This event handler can be reimplemented in a subclass to receive custom events. More...
 
virtual void disconnectNotify (const char *signal)
 This virtual function is called when something has been disconnected from signal in this object. More...
 
 QObject (QObjectPrivate &dd, QObject *parent=0)
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal. More...
 
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. More...
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *)
 This event handler can be reimplemented in a subclass to receive timer events for the object. More...
 

Private Functions

QUnixSocketoperator= (const QUnixSocket &)
 
 QUnixSocket (const QUnixSocket &)
 

Properties

QUnixSocketPrivated
 

Additional Inherited Members

- Public Slots inherited from QObject
void deleteLater ()
 Schedules this object for deletion. More...
 
- Static Public Functions inherited from QObject
static bool connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 Creates a connection of the given type from the signal in the sender object to the method in the receiver object. More...
 
static bool connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 Disconnects signal in object sender from method in object receiver. More...
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static uint registerUserData ()
 
static QString tr (const char *sourceText, const char *comment=0, int n=-1)
 
static QString trUtf8 (const char *sourceText, const char *comment=0, int n=-1)
 
- Static Public Variables inherited from QObject
static const QMetaObject staticMetaObject
 This variable stores the meta-object for the class. More...
 
- Protected Variables inherited from QObject
QScopedPointer< QObjectDatad_ptr
 
- Static Protected Variables inherited from QObject
static const QMetaObject staticQtMetaObject
 

Detailed Description

The QUnixSocket class provides a Unix domain socket.

Warning
This function is not part of the public interface.
This function is not part of the public interface. :: :: ::

Unix domain sockets provide an efficient mechanism for communications between Unix processes on the same machine. Unix domain sockets support a reliable, stream-oriented, connection-oriented transport protocol, much like TCP sockets. Unlike IP based sockets, the connection endpoint of a Unix domain socket is a file on disk of type socket.

In addition to transporting raw data bytes, Unix domain sockets are able to transmit special ancillary data. The two types of ancillary data supported by the QUnixSocket class are:

Because of the need to support ancillary data, QUnixSocket is not a QIODevice, like QTcpSocket and QUdpSocket. Instead, QUnixSocket contains a number of read and write methods that clients must invoke directly. Rather than returning raw data bytes, QUnixSocket::read() returns QUnixSocketMessage instances that encapsulate the message's byte data and any other ancillary data.

Ancillary data is transmitted "out of band". Every QUnixSocketMessage received will have credential data associated with it that the client can access through calls to QUnixSocketMessage::processId() , QUnixSocketMessage::groupId() and QUnixSocketMessage::userId() . Likewise, message creators can set the credential data to send through calls to QUnixSocketMessage::setProcessId() , QUnixSocketMessage::setGroupId() and QUnixSocketMessage::setUserId() respectively. The authenticity of the credential values is verified by the system kernel and cannot be fabricated by unprivileged processes. Only processes running as the root user can specify credential data that does not match the sending process.

Unix file descriptors, known as "rights data", transmitted between processes appear as though they had been dup(2)'d between the two. As Unix domain sockets present a continuous stream of bytes to the receiver, the rights data - which is transmitted out of band - must be "slotted" in at some point. The rights data is logically associated with the first byte - called the anchor byte - of the QUnixSocketMessage to which they are attached. Received rights data will be available from the QUnixSocketMessage::rights() method for the QUnixSocketMessage instance that contains the anchor byte.

In addition to a QUnixSocket::write() that takes a QUnixSocketMessage instance - allowing a client to transmit both byte and rights data - a number of convenience overloads are provided for use when only transmitting simple byte data. Unix requires that at least one byte of raw data be transmitted in order to send rights data. A QUnixSocketMessage instance with rights data, but no byte data, cannot be transmitted.

Unix sockets present a stream interface, such that, for example, a single six byte transmission might be received as two three byte messages. Rights data, on the other hand, is conceptually transmitted as unfragmentable datagrams. If the receiving buffer is not large enough to contain all the transmitted rights information, the data is truncated and irretreivably lost. Users should use the QUnixSocket::setRightsBufferSize() method to control the buffer size used for this data, and develop protocols that avoid the problem. If the buffer size is too small and rights data is truncated, the QUnixSocketMessage::rightsWereTruncated() flag will be set.

See also
QUnixSocketMessage QUnixSocketRights

Definition at line 125 of file qunixsocket_p.h.

Enumerations

◆ SocketError

The SocketError enumeration represents the various errors that can occur on a Unix domain socket.

The most recent error for the socket is available through the QUnixSocket::error() method.

  • NoError No error has occurred.
  • InvalidPath An invalid path endpoint was passed to QUnixSocket::connect() . As defined by unix(7), invalid paths include an empty path, or what more than 107 characters long.
  • ResourceError An error acquiring or manipulating the system's socket resources occurred. For example, if the process runs out of available socket descriptors, a ResourceError will occur.
  • NonexistentPath The endpoing passed to QUnixSocket::connect() does not refer to a Unix domain socket entity on disk.
  • ConnectionRefused The connection to the specified endpoint was refused. Generally this means that there is no server listening on that endpoint.
  • UnknownError An unknown error has occurred.
  • ReadFailure An error occurred while reading bytes from the connection.
  • WriteFailure An error occurred while writing bytes into the connection.
Enumerator
NoError 
InvalidPath 
ResourceError 
NonexistentPath 
ConnectionRefused 
UnknownError 
ReadFailure 
WriteFailure 

Definition at line 143 of file qunixsocket_p.h.

◆ SocketState

The SocketState enumeration represents the connection state of a QUnixSocket instance.

  • UnconnectedState The connection is not established.
  • ConnectedState The connection is established.
  • ClosingState The connection is being closed, following a call to QUnixSocket::close() . While closing, any pending data will be transmitted, but further writes by the application will be refused.
Enumerator
UnconnectedState 
HostLookupState 
ConnectingState 
ConnectedState 
BoundState 
ClosingState 
ListeningState 

Definition at line 133 of file qunixsocket_p.h.

Constructors and Destructors

◆ QUnixSocket() [1/3]

QUnixSocket::QUnixSocket ( QObject parent = 0)

Construct a QUnixSocket instance, with parent.

The read buffer is initially set to 1024 bytes, and the rights buffer to 0 entries.

See also
QUnixSocket::readBufferSize() QUnixSocket::rightsBufferSize()

Definition at line 898 of file qunixsocket.cpp.

899 : QIODevice(parent), d(new QUnixSocketPrivate(this))
900 {
904 }
void setOpenMode(OpenMode openMode)
Sets the OpenMode of the device to openMode.
Definition: qiodevice.cpp:477
QUnixSocketPrivate * d
void setReadBufferSize(qint64 size)
Sets the size of the socket&#39;s read buffer in bytes.
#define QUNIXSOCKET_DEFAULT_READBUFFER
void setRightsBufferSize(qint64 size)
Sets the size of the socket&#39;s rights buffer in rights entries.
QIODevice()
Constructs a QIODevice object.
Definition: qiodevice.cpp:390
#define QUNIXSOCKET_DEFAULT_ANCILLARYBUFFER

◆ QUnixSocket() [2/3]

QUnixSocket::QUnixSocket ( qint64  readBufferSize,
qint64  rightsBufferSize,
QObject parent = 0 
)

Construct a QUnixSocket instance, with parent.

The read buffer is initially set to readBufferSize bytes, and the rights buffer to rightsBufferSize entries.

See also
QUnixSocket::readBufferSize() QUnixSocket::rightsBufferSize()

Definition at line 914 of file qunixsocket.cpp.

916 : QIODevice(parent), d(new QUnixSocketPrivate(this))
917 {
919 
923 }
void setOpenMode(OpenMode openMode)
Sets the OpenMode of the device to openMode.
Definition: qiodevice.cpp:477
QUnixSocketPrivate * d
qint64 readBufferSize() const
Returns the size of the read buffer in bytes.
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
void setReadBufferSize(qint64 size)
Sets the size of the socket&#39;s read buffer in bytes.
void setRightsBufferSize(qint64 size)
Sets the size of the socket&#39;s rights buffer in rights entries.
QIODevice()
Constructs a QIODevice object.
Definition: qiodevice.cpp:390
qint64 rightsBufferSize() const
Returns the size of the rights buffer in rights entries.

◆ ~QUnixSocket()

QUnixSocket::~QUnixSocket ( )
virtual

Destroys the QUnixSocket instance.

Any unsent data is discarded.

Definition at line 928 of file qunixsocket.cpp.

929 {
930  abort();
931  delete d;
932 }
void abort()
Abort the connection.
QUnixSocketPrivate * d

◆ QUnixSocket() [3/3]

QUnixSocket::QUnixSocket ( const QUnixSocket )
private

Functions

◆ abort()

void QUnixSocket::abort ( )

Abort the connection.

This will immediately disconnect (if connected) and discard any pending data. Following a call to QUnixSocket::abort() the object will always be in the disconnected state.

See also
QUnixSocket::close()

Definition at line 1133 of file qunixsocket.cpp.

Referenced by connect(), setSocketDescriptor(), QUnixSocketPrivate::timerEvent(), waitForBytesWritten(), waitForReadyRead(), and ~QUnixSocket().

1134 {
1136 
1137  // We want to be able to use QUnixSocket::abort() to cleanup our state but
1138  // also preserve the error message that caused the abort. It is not
1139  // possible to reorder code to do this:
1140  // abort();
1141  // d->error = SomeError
1142  // as QUnixSocket::abort() might emit a signal and we need the error to be
1143  // set within that signal. So, if we want an error message to be preserved
1144  // across a *single* call to abort(), we set the
1145  // QUnixSocketPrivate::CausedAbort flag in the error.
1149  else
1150  d->error = NoError;
1151 
1152  if( UnconnectedState == d->state) return;
1153 
1154 #ifdef QUNIXSOCKET_DEBUG
1155  int closerv =
1156 #endif
1157  ::close(d->fd);
1158 #ifdef QUNIXSOCKET_DEBUG
1159  if(0 != closerv) {
1160  qDebug() << "QUnixSocket: Unable to close socket during abort ("
1161  << strerror(errno) << ')';
1162  }
1163 #endif
1164 
1165  // Reset variables
1166  d->fd = -1;
1168  d->dataBufferLength = 0;
1169  d->flushAncillary();
1170  d->address = QByteArray();
1171  if(d->readNotifier) {
1172  d->readNotifier->setEnabled(false);
1174  }
1175  if(d->writeNotifier) {
1176  d->writeNotifier->setEnabled(false);
1178  }
1179  d->readNotifier = 0;
1180  d->writeNotifier = 0;
1181  d->writeQueue.clear();
1182  d->writeQueueBytes = 0;
1183  if(d->closingTimer) {
1185  }
1186  d->closingTimer = 0;
1188 }
QSocketNotifier * readNotifier
void setOpenMode(OpenMode openMode)
Sets the OpenMode of the device to openMode.
Definition: qiodevice.cpp:477
QUnixSocket::SocketError error
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
QUnixSocketPrivate * d
void close()
Close the connection.
QQueue< QUnixSocketMessage > writeQueue
unsigned int dataBufferLength
Q_CORE_EXPORT void qDebug(const char *,...)
QUnixSocket::SocketState state
#define emit
Definition: qobjectdefs.h:76
SocketError
The SocketError enumeration represents the various errors that can occur on a Unix domain socket...
void clear()
Removes all items from the list.
Definition: qlist.h:764
unsigned int writeQueueBytes
void stateChanged(SocketState socketState)
This signal is emitted each time the socket changes connection state.
void setEnabled(bool)
If enable is true, the notifier is enabled; otherwise the notifier is disabled.
QSocketNotifier * writeNotifier
void deleteLater()
Schedules this object for deletion.
Definition: qobject.cpp:2145
int errno
void killTimer(int id)
Kills the timer with timer identifier, id.
Definition: qobject.cpp:1650

◆ address()

QByteArray QUnixSocket::address ( ) const

Returns the Unix path address passed to QUnixSocket::connect() .

This method will return an empty path if the object is in the Unconnected QUnixSocket::state(){state } or was connected through a call to QUnixSocket::setSocketDescriptor()

See also
QUnixSocket::connect() QUnixSocket::setSocketDescriptor()

Definition at line 1258 of file qunixsocket.cpp.

1259 {
1260  return d->address;
1261 }
QUnixSocketPrivate * d

◆ bytesAvailable()

qint64 QUnixSocket::bytesAvailable ( ) const
virtual

Returns the number of bytes available for immediate retrieval through a call to QUnixSocket::read() .

Reimplemented from QIODevice.

Definition at line 1267 of file qunixsocket.cpp.

1268 {
1270 }
QUnixSocketPrivate * d
unsigned int dataBufferLength
virtual qint64 bytesAvailable() const
Returns the number of bytes that are available for reading.
Definition: qiodevice.cpp:752

◆ bytesToWrite()

qint64 QUnixSocket::bytesToWrite ( ) const
virtual

Returns the number of enqueued bytes still to be written to the socket.

Reimplemented from QIODevice.

Definition at line 1275 of file qunixsocket.cpp.

1276 {
1277  return d->writeQueueBytes;
1278 }
QUnixSocketPrivate * d
unsigned int writeQueueBytes

◆ canReadLine()

bool QUnixSocket::canReadLine ( ) const
virtual
Warning
This function is not part of the public interface.

Reimplemented from QIODevice.

Definition at line 1608 of file qunixsocket.cpp.

1609 {
1610  for(unsigned int ii = 0; ii < d->dataBufferLength; ++ii)
1611  if(d->dataBuffer[ii] == '\n') return true;
1612  return false;
1613 }
QUnixSocketPrivate * d
unsigned int dataBufferLength

◆ close()

void QUnixSocket::close ( )
virtual

Close the connection.

The instance will enter the Closing QUnixSocket::state(){state } until all pending data has been transmitted, at which point it will enter the Unconnected state.

Even if there is no pending data for transmission, the object will never jump directly to Disconnect without first passing through the Closing state.

See also
QUnixSocket::abort()

Reimplemented from QIODevice.

Definition at line 1201 of file qunixsocket.cpp.

Referenced by abort().

1202 {
1203  if(ConnectedState != state()) return;
1204 
1205  d->state = ClosingState;
1206  if(d->writeQueue.isEmpty()) {
1207  d->closingTimer = d->startTimer(0); // Start a timer to "fake"
1208  // completing writes
1209  }
1211 }
int startTimer(int interval)
Starts a timer and returns a timer identifier, or returns zero if it could not start a timer...
Definition: qobject.cpp:1623
QUnixSocketPrivate * d
QQueue< QUnixSocketMessage > writeQueue
bool isEmpty() const
Returns true if the list contains no items; otherwise returns false.
Definition: qlist.h:152
QUnixSocket::SocketState state
SocketState state() const
Returns the connection state of this instance.
#define emit
Definition: qobjectdefs.h:76
void stateChanged(SocketState socketState)
This signal is emitted each time the socket changes connection state.

◆ connect()

bool QUnixSocket::connect ( const QByteArray path)

Attempt to connect to path.

This method is synchronous and will return true if the connection succeeds and false otherwise. In the case of failure, QUnixSocket::error() will be set accordingly.

Any existing connection will be aborted, and all pending data will be discarded.

See also
QUnixSocket::close() QUnixSocket::abort() QUnixSocket::error()

Definition at line 946 of file qunixsocket.cpp.

Referenced by QWSSocket::connectToLocalFile().

947 {
948  int _true;
949  int crv;
950 #ifdef QUNIXSOCKET_DEBUG
951  qDebug() << "QUnixSocket: Connect requested to '"
952  << path << '\'';
953 #endif
954 
955  abort(); // Reset any existing connection
956 
957  if(UnconnectedState != d->state) // abort() caused a signal and someone messed
958  // with us. We'll assume they know what
959  // they're doing and bail. Alternative is to
960  // have a special "Connecting" state
961  return false;
962 
963 
964  if(path.isEmpty() || path.size() > UNIX_PATH_MAX) {
965  d->error = InvalidPath;
966  return false;
967  }
968 
969  // Create the socket
970  d->fd = ::socket(PF_UNIX, SOCK_STREAM, 0);
971  if(-1 == d->fd) {
972 #ifdef QUNIXSOCKET_DEBUG
973  qDebug() << "QUnixSocket: Unable to create socket ("
974  << strerror(errno) << ')';
975 #endif
976  d->error = ResourceError;
977  goto connect_error;
978  }
979 
980  // Set socket options
981  _true = 1;
982  crv = ::setsockopt(d->fd, SOL_SOCKET, SO_PASSCRED, (void *)&_true,
983  sizeof(int));
984  if(-1 == crv) {
985 #ifdef QUNIXSOCKET_DEBUG
986  qDebug() << "QUnixSocket: Unable to configure socket ("
987  << ::strerror(errno) << ')';
988 #endif
989  d->error = ResourceError;
990 
991  goto connect_error;
992  }
993 
994  // Construct our unix address
995  struct ::sockaddr_un addr;
996  addr.sun_family = AF_UNIX;
997  ::memcpy(addr.sun_path, path.data(), path.size());
998  if(path.size() < UNIX_PATH_MAX)
999  addr.sun_path[path.size()] = '\0';
1000 
1001  // Attempt the connect
1002  crv = ::connect(d->fd, (sockaddr *)&addr, sizeof(sockaddr_un));
1003  if(-1 == crv) {
1004 #ifdef QUNIXSOCKET_DEBUG
1005  qDebug() << "QUnixSocket: Unable to connect ("
1006  << ::strerror(errno) << ')';
1007 #endif
1008  if(ECONNREFUSED == errno)
1010  else if(ENOENT == errno)
1011  d->error = NonexistentPath;
1012  else
1013  d->error = UnknownError;
1014 
1015  goto connect_error;
1016  }
1017 
1018  // We're connected!
1019  d->address = path;
1020  d->state = ConnectedState;
1023  QObject::connect(d->readNotifier, SIGNAL(activated(int)),
1024  d, SLOT(readActivated()));
1025  QObject::connect(d->writeNotifier, SIGNAL(activated(int)),
1026  d, SLOT(writeActivated()));
1027  d->readNotifier->setEnabled(true);
1028  d->writeNotifier->setEnabled(false);
1031 
1032 #ifdef QUNIXSOCKET_DEBUG
1033  qDebug() << "QUnixSocket: Connected to " << path;
1034 #endif
1035  return true;
1036 
1037 connect_error: // Cleanup failed connection
1038  if(-1 != d->fd) {
1039 #ifdef QUNIXSOCKET_DEBUG
1040  int closerv =
1041 #endif
1042  QT_CLOSE(d->fd);
1043 #ifdef QUNIXSOCKET_DEBUG
1044  if(0 != closerv) {
1045  qDebug() << "QUnixSocket: Unable to close file descriptor after "
1046  "failed connect (" << ::strerror(errno) << ')';
1047  }
1048 #endif
1049  }
1050  d->fd = -1;
1051  return false;
1052 }
void abort()
Abort the connection.
QSocketNotifier * readNotifier
void setOpenMode(OpenMode openMode)
Sets the OpenMode of the device to openMode.
Definition: qiodevice.cpp:477
QUnixSocket::SocketError error
char * data()
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:429
#define SLOT(a)
Definition: qobjectdefs.h:226
QUnixSocketPrivate * d
The QSocketNotifier class provides support for monitoring activity on a file descriptor.
Q_CORE_EXPORT void qDebug(const char *,...)
QUnixSocket::SocketState state
#define SIGNAL(a)
Definition: qobjectdefs.h:227
static bool connect(const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
Creates a connection of the given type from the signal in the sender object to the method in the rece...
Definition: qobject.cpp:2580
#define emit
Definition: qobjectdefs.h:76
void stateChanged(SocketState socketState)
This signal is emitted each time the socket changes connection state.
void setEnabled(bool)
If enable is true, the notifier is enabled; otherwise the notifier is disabled.
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402
bool connect(const QByteArray &path)
Attempt to connect to path.
bool isEmpty() const
Returns true if the byte array has size 0; otherwise returns false.
Definition: qbytearray.h:421
QSocketNotifier * writeNotifier
int errno
#define UNIX_PATH_MAX
Definition: qunixsocket.cpp:63
#define QT_CLOSE
Definition: qcore_unix_p.h:304

◆ error()

QUnixSocket::SocketError QUnixSocket::error ( ) const

Returns the last error to have occurred on this object.

This method is not destructive, so multiple calls to QUnixSocket::error() will return the same value. The error is only reset by a call to QUnixSocket::connect() or QUnixSocket::abort()

Definition at line 1236 of file qunixsocket.cpp.

Referenced by QWSSocket::errorString(), QWSSocket::forwardStateChange(), QUnixSocketPrivate::readActivated(), and QUnixSocketPrivate::writeActivated().

1237 {
1238  return (QUnixSocket::SocketError)
1239  (d->error & ~QUnixSocketPrivate::CausedAbort);
1240 }
QUnixSocket::SocketError error
QUnixSocketPrivate * d
SocketError
The SocketError enumeration represents the various errors that can occur on a Unix domain socket...

◆ flush()

bool QUnixSocket::flush ( )

This function writes as much as possible from the internal write buffer to the underlying socket, without blocking.

If any data was written, this function returns true; otherwise false is returned.

Definition at line 1219 of file qunixsocket.cpp.

1220 {
1221  // This needs to have the same semantics as QAbstractSocket, if it is to
1222  // be used interchangeably with that class.
1223  if (d->writeQueue.isEmpty())
1224  return false;
1225 
1226  d->writeActivated();
1227  return true;
1228 }
QUnixSocketPrivate * d
QQueue< QUnixSocketMessage > writeQueue
bool isEmpty() const
Returns true if the list contains no items; otherwise returns false.
Definition: qlist.h:152

◆ isSequential()

bool QUnixSocket::isSequential ( ) const
virtual
Warning
This function is not part of the public interface.

Reimplemented from QIODevice.

Definition at line 1474 of file qunixsocket.cpp.

1475 {
1476  return true;
1477 }

◆ operator=()

QUnixSocket& QUnixSocket::operator= ( const QUnixSocket )
private

◆ read() [1/3]

qint64 QUnixSocket::read ( char *  data,
qint64  maxSize 
)
inline

Definition at line 174 of file qunixsocket_p.h.

Referenced by QAuthDevice::recvReadyRead().

175  { return QIODevice::read(data, maxSize); }
qint64 read(char *data, qint64 maxlen)
Reads at most maxSize bytes from the device into data, and returns the number of bytes read...
Definition: qiodevice.cpp:791
static const char * data(const QByteArray &arr)

◆ read() [2/3]

QByteArray QUnixSocket::read ( qint64  maxSize)
inline

Definition at line 176 of file qunixsocket_p.h.

177  { return QIODevice::read(maxSize); }
qint64 read(char *data, qint64 maxlen)
Reads at most maxSize bytes from the device into data, and returns the number of bytes read...
Definition: qiodevice.cpp:791

◆ read() [3/3]

QUnixSocketMessage QUnixSocket::read ( )

Return the next available message, or an empty message if none is available.

To avoid retrieving empty messages, applications should connect to the QUnixSocket::readyRead() signal to be notified when new messages are available or periodically poll the QUnixSocket::bytesAvailable() method.

See also
QUnixSocket::readyRead() QUnixSocket::bytesAvailable()

Definition at line 1409 of file qunixsocket.cpp.

1410 {
1412  if(!d->dataBufferLength)
1413  return data;
1414 
1416 
1417  // Bytes are easy
1419 
1420  // Extract ancillary data
1422 
1423  ::cmsghdr * h = (::cmsghdr *)CMSG_FIRSTHDR(&(d->message));
1424  while(h) {
1425 
1426  if(SCM_CREDENTIALS == h->cmsg_type) {
1427  ::ucred * cred = (::ucred *)CMSG_DATA(h);
1428 #ifdef QUNIXSOCKET_DEBUG
1429  qDebug( "Credentials recd: pid %lu - gid %lu - uid %lu",
1430  cred->pid, cred->gid, cred->uid );
1431 #endif
1432  data.d->pid = cred->pid;
1433  data.d->gid = cred->gid;
1434  data.d->uid = cred->uid;
1435 
1436  } else if(SCM_RIGHTS == h->cmsg_type) {
1437 
1438  int * fds = (int *)CMSG_DATA(h);
1439  int numFds = (h->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1440 
1441  for(int ii = 0; ii < numFds; ++ii) {
1442  QUnixSocketRights qusr(fds[ii], 0);
1443  a.append(qusr);
1444  }
1445 
1446  } else {
1447 
1448 #ifdef QUNIXSOCKET_DEBUG
1449  qFatal("QUnixSocket: Unknown ancillary data type (%d) received.",
1450  h->cmsg_type);
1451 #endif
1452 
1453  }
1454 
1455  h = (::cmsghdr *)CMSG_NXTHDR(&(d->message), h);
1456  }
1457 
1458  if(d->message.msg_flags & MSG_CTRUNC) {
1461  }
1462 
1463  if(!a.isEmpty())
1464  data.d->rights = a;
1465 
1466  d->dataBufferLength = 0;
1467  d->messageValid = false;
1468  d->readNotifier->setEnabled(true);
1469 
1470  return data;
1471 }
AncillaryDataState state
QSocketNotifier * readNotifier
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
QUnixSocketPrivate * d
long ASN1_INTEGER_get ASN1_INTEGER * a
The QUnixSocketRights class encapsulates QUnixSocket rights data.
Definition: qunixsocket_p.h:73
bool isEmpty() const
Returns true if the list contains no items; otherwise returns false.
Definition: qlist.h:152
unsigned int dataBufferLength
Q_CORE_EXPORT void qDebug(const char *,...)
void append(const T &t)
Inserts value at the end of the list.
Definition: qlist.h:507
QList< QUnixSocketRights > rights
static const char * data(const QByteArray &arr)
QSharedDataPointer< QUnixSocketMessagePrivate > d
Q_CORE_EXPORT void qFatal(const char *,...)
void setEnabled(bool)
If enable is true, the notifier is enabled; otherwise the notifier is disabled.
void setBytes(const QByteArray &)
Set the data portion of the message to bytes.
The QUnixSocketMessage class encapsulates a message sent or received through the QUnixSocket class...
Definition: qunixsocket_p.h:92

◆ readBufferSize()

qint64 QUnixSocket::readBufferSize ( ) const

Returns the size of the read buffer in bytes.

The read buffer size determines the amount of byte data that can be read from the socket in one go. The read buffer size caps the maximum value that can be returned by QUnixSocket::bytesAvailable() and will always be greater than zero. By default, the read buffer size is 1024 bytes.

The size of the read buffer is independent of the rights buffer, which can be queried by QUnixSocket::rightsBufferSize() .

See also
QUnixSocket::setReadBufferSize()

Definition at line 1292 of file qunixsocket.cpp.

1293 {
1294  return d->dataBufferCapacity;
1295 }
QUnixSocketPrivate * d
unsigned int dataBufferCapacity

◆ readData()

qint64 QUnixSocket::readData ( char *  data,
qint64  maxSize 
)
protectedvirtual
Warning
This function is not part of the public interface.

Implements QIODevice.

Definition at line 1616 of file qunixsocket.cpp.

1617 {
1618  Q_ASSERT(data);
1619  if(0 >= maxSize) return 0;
1620  if(!d->dataBufferLength) return 0;
1621 
1622  // Read data
1623  unsigned int size = d->dataBufferLength>maxSize?maxSize:d->dataBufferLength;
1624  memcpy(data, d->dataBuffer, size);
1625  if(size == d->dataBufferLength) {
1626  d->dataBufferLength = 0;
1627  } else {
1628  memmove(d->dataBuffer, d->dataBuffer + size, d->dataBufferLength - size);
1629  d->dataBufferLength -= size;
1630  }
1631 
1632 
1633  // Flush ancillary
1634  d->flushAncillary();
1635 
1636  if(0 == d->dataBufferLength)
1637  d->readNotifier->setEnabled(true);
1638 
1639  return size;
1640 }
virtual qint64 size() const
For open random-access devices, this function returns the size of the device.
Definition: qiodevice.cpp:642
QSocketNotifier * readNotifier
QUnixSocketPrivate * d
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
unsigned int dataBufferLength
static const char * data(const QByteArray &arr)
void setEnabled(bool)
If enable is true, the notifier is enabled; otherwise the notifier is disabled.

◆ rightsBufferSize()

qint64 QUnixSocket::rightsBufferSize ( ) const

Returns the size of the rights buffer in rights entries.

The rights buffer size determines the number of rights transferences that can be received in any message. Unlike byte stream data which can be fragmented into many smaller messages if the read buffer is not large enough to contain all the available data, rights data is transmitted as unfragmentable datagrams. If the rights buffer is not large enough to contain this unfragmentable datagram, the datagram will be truncated and rights data irretrievably lost. If truncation occurs, the QUnixSocketMessage::rightsWereTruncated() flag will be set. By default the rights buffer size is 0 entries - rights data cannot be received.

The size of the rights buffer is independent of the read buffer, which can be queried by QUnixSocket::readBufferSize() .

See also
QUnixSocket::setRightsBufferSize()

Definition at line 1334 of file qunixsocket.cpp.

1335 {
1336  return d->ancillaryBufferCount;
1337 }
unsigned int ancillaryBufferCount
QUnixSocketPrivate * d

◆ setReadBufferSize()

void QUnixSocket::setReadBufferSize ( qint64  size)

Sets the size of the socket's read buffer in bytes.

The size of the read buffer is independent of the rights buffer, which can be set by QUnixSocket::setRightsBufferSize() .

Attempting to reduce the buffer size while bytes are available for reading (ie. while the buffer is in use) will fail.

See also
QUnixSocket::readBufferSize()

Definition at line 1308 of file qunixsocket.cpp.

Referenced by QUnixSocket().

1309 {
1310  Q_ASSERT(size > 0);
1311  if(size == d->dataBufferCapacity || d->dataBufferLength) return;
1312  if(d->dataBuffer) delete [] d->dataBuffer;
1313  d->dataBuffer = new char[size];
1315 }
virtual qint64 size() const
For open random-access devices, this function returns the size of the device.
Definition: qiodevice.cpp:642
QUnixSocketPrivate * d
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
unsigned int dataBufferLength
unsigned int dataBufferCapacity

◆ setRightsBufferSize()

void QUnixSocket::setRightsBufferSize ( qint64  size)

Sets the size of the socket's rights buffer in rights entries.

The size of the rights buffer is independent of the read buffer, which can be set by QUnixSocket::setReadBufferSize() .

Attempting to reduce the buffer size while bytes are available for reading (ie. while the buffer is in use) will fail.

See also
QUnixSocket::rightsBufferSize()

Definition at line 1350 of file qunixsocket.cpp.

Referenced by QUnixSocket().

1351 {
1352  Q_ASSERT(size >= 0);
1353 
1354  if((size == d->ancillaryBufferCount || d->dataBufferLength) &&
1355  d->ancillaryBuffer)
1356  return;
1357 
1358  qint64 byteSize = CMSG_SPACE(sizeof(::ucred)) +
1359  CMSG_SPACE(size * sizeof(int));
1360 
1361  if(d->ancillaryBuffer) delete [] d->ancillaryBuffer;
1362  d->ancillaryBuffer = new char[byteSize];
1364 }
unsigned int ancillaryBufferCount
virtual qint64 size() const
For open random-access devices, this function returns the size of the device.
Definition: qiodevice.cpp:642
QUnixSocketPrivate * d
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
unsigned int dataBufferLength
__int64 qint64
Definition: qglobal.h:942

◆ setSocketDescriptor()

bool QUnixSocket::setSocketDescriptor ( int  socketDescriptor)

Sets the socket descriptor to use to socketDescriptor, bypassing QUnixSocket's connection infrastructure, and return true on success and false on failure.

socketDescriptor must be in the connected state, and must be a Unix domain socket descriptor. Following a successful call to this method, the QUnixSocket instance will be in the Connected state and will have assumed ownership of socketDescriptor.

Any existing connection will be aborted, and all pending data will be discarded.

See also
QUnixSocket::connect()

Definition at line 1067 of file qunixsocket.cpp.

1068 {
1069  abort();
1070 
1071  if(UnconnectedState != state()) // See QUnixSocket::connect()
1072  return false;
1073 
1074  // Attempt to set the socket options
1075  if(-1 == socketDescriptor) {
1076 #ifdef QUNIXSOCKET_DEBUG
1077  qDebug() << "QUnixSocket: User provided socket is invalid";
1078 #endif
1079  d->error = ResourceError;
1080  return false;
1081  }
1082 
1083  // Set socket options
1084  int _true = 1;
1085  int crv = ::setsockopt(socketDescriptor, SOL_SOCKET,
1086  SO_PASSCRED, (void *)&_true, sizeof(int));
1087  if(-1 == crv) {
1088 #ifdef QUNIXSOCKET_DEBUG
1089  qDebug() << "QUnixSocket: Unable to configure client provided socket ("
1090  << ::strerror(errno) << ')';
1091 #endif
1092  d->error = ResourceError;
1093 
1094  return false;
1095  }
1096 
1097  d->fd = socketDescriptor;
1098  d->state = ConnectedState;
1099  d->address = QByteArray();
1103  QObject::connect(d->readNotifier, SIGNAL(activated(int)),
1104  d, SLOT(readActivated()));
1105  QObject::connect(d->writeNotifier, SIGNAL(activated(int)),
1106  d, SLOT(writeActivated()));
1107  d->readNotifier->setEnabled(true);
1108  d->writeNotifier->setEnabled(false);
1110 
1111  return true;
1112 }
void abort()
Abort the connection.
QSocketNotifier * readNotifier
void setOpenMode(OpenMode openMode)
Sets the OpenMode of the device to openMode.
Definition: qiodevice.cpp:477
QUnixSocket::SocketError error
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
#define SLOT(a)
Definition: qobjectdefs.h:226
QUnixSocketPrivate * d
The QSocketNotifier class provides support for monitoring activity on a file descriptor.
Q_CORE_EXPORT void qDebug(const char *,...)
QUnixSocket::SocketState state
#define SIGNAL(a)
Definition: qobjectdefs.h:227
int socketDescriptor() const
Returns the socket descriptor currently in use.
static bool connect(const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
Creates a connection of the given type from the signal in the sender object to the method in the rece...
Definition: qobject.cpp:2580
SocketState state() const
Returns the connection state of this instance.
#define emit
Definition: qobjectdefs.h:76
void stateChanged(SocketState socketState)
This signal is emitted each time the socket changes connection state.
void setEnabled(bool)
If enable is true, the notifier is enabled; otherwise the notifier is disabled.
QSocketNotifier * writeNotifier
int errno

◆ socketDescriptor()

int QUnixSocket::socketDescriptor ( ) const

Returns the socket descriptor currently in use.

This method will return -1 if the QUnixSocket instance is in the UnconnectedState QUnixSocket::state(){state. }

See also
QUnixSocket::setSocketDescriptor()

Definition at line 1120 of file qunixsocket.cpp.

Referenced by setSocketDescriptor().

1121 {
1122  return d->fd;
1123 }
QUnixSocketPrivate * d

◆ state()

QUnixSocket::SocketState QUnixSocket::state ( ) const

Returns the connection state of this instance.

Definition at line 1245 of file qunixsocket.cpp.

Referenced by close(), setSocketDescriptor(), and write().

1246 {
1247  return d->state;
1248 }
QUnixSocketPrivate * d
QUnixSocket::SocketState state

◆ stateChanged

QUnixSocket::stateChanged ( SocketState  socketState)
signal

This signal is emitted each time the socket changes connection state.

socketState will be set to the socket's new state.

Referenced by abort(), close(), connect(), and setSocketDescriptor().

◆ waitForBytesWritten()

bool QUnixSocket::waitForBytesWritten ( int  msecs = 300)
virtual

For buffered devices, this function waits until a payload of buffered written data has been written to the device and the bytesWritten() signal has been emitted, or until msecs milliseconds have passed.

If msecs is -1, this function will not time out. For unbuffered devices, it returns immediately.

Returns true if a payload of data was written to the device; otherwise returns false (i.e. if the operation timed out, or if an error occurred).

This function can operate without an event loop. It is useful when writing non-GUI applications and when performing I/O operations in a non-GUI thread.

If called from within a slot connected to the bytesWritten() signal, bytesWritten() will not be reemitted.

Reimplement this function to provide a blocking API for a custom device. The default implementation does nothing, and returns false.

Warning
Calling this function from the main (GUI) thread might cause your user interface to freeze.
See also
waitForReadyRead()

Reimplemented from QIODevice.

Definition at line 1533 of file qunixsocket.cpp.

1534 {
1535  if(UnconnectedState == d->state)
1536  return false;
1537 
1538  Q_ASSERT(-1 != d->fd);
1539 
1540  if ( d->writeQueue.isEmpty() )
1541  return true;
1542 
1543  QTime stopWatch;
1544  stopWatch.start();
1545 
1546  while ( true )
1547  {
1548  fd_set fdwrite;
1549  FD_ZERO(&fdwrite);
1550  FD_SET(d->fd, &fdwrite);
1551  int timeout = msecs < 0 ? 0 : msecs - stopWatch.elapsed();
1552  struct timeval tv;
1553  struct timeval *ptrTv = 0;
1554  if ( -1 != msecs )
1555  {
1556  tv.tv_sec = timeout / 1000;
1557  tv.tv_usec = (timeout % 1000) * 1000;
1558  ptrTv = &tv;
1559  }
1560 
1561  int rv = ::select(d->fd + 1, 0, &fdwrite, 0, ptrTv);
1562  switch ( rv )
1563  {
1564  case 0:
1565  // timeout
1566  return false;
1567  case 1:
1568  {
1569  // ok to write
1571  if (bytesWritten == 0) {
1572  // We need to retry
1573  int delay = 1;
1574  do {
1575  if (-1 != msecs) {
1576  timeout = msecs - stopWatch.elapsed();
1577  if (timeout <= 0) {
1578  // We have exceeded our allotted time
1579  return false;
1580  } else {
1581  if (delay > timeout)
1582  delay = timeout;
1583  }
1584  }
1585 
1586  // Pause before we make another attempt to send
1587  ::usleep(delay * 1000);
1588  if (delay < 1024)
1589  delay *= 2;
1590 
1591  bytesWritten = d->writeActivated();
1592  } while (bytesWritten == 0);
1593  }
1594  return (bytesWritten != -1);
1595  }
1596  default:
1597  // error - or an uncaught signal!!!!!!!!!
1598  if ( rv == EINTR )
1599  continue;
1600  abort();
1601  return false;
1602  }
1603  }
1604  return false; // fix warnings
1605 }
void abort()
Abort the connection.
void start()
Sets this time to the current time.
Definition: qdatetime.cpp:2070
QUnixSocketPrivate * d
int select(int, fd_set *, fd_set *, fd_set *, struct timeval *)
void bytesWritten(qint64 bytes)
This signal is emitted every time a payload of data has been written to the device.
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
QQueue< QUnixSocketMessage > writeQueue
bool isEmpty() const
Returns true if the list contains no items; otherwise returns false.
Definition: qlist.h:152
QUnixSocket::SocketState state
The QTime class provides clock time functions.
Definition: qdatetime.h:148
__int64 qint64
Definition: qglobal.h:942
int elapsed() const
Returns the number of milliseconds that have elapsed since the last time start() or restart() was cal...
Definition: qdatetime.cpp:2123

◆ waitForReadyRead()

bool QUnixSocket::waitForReadyRead ( int  msecs = 300)
virtual
Warning
This function is not part of the public interface.

Reimplemented from QIODevice.

Definition at line 1480 of file qunixsocket.cpp.

1481 {
1482  if(UnconnectedState == d->state)
1483  return false;
1484 
1485  if(d->messageValid) {
1486  return true;
1487  }
1488 
1489  Q_ASSERT(-1 != d->fd);
1490 
1491  int timeout = msecs;
1492  struct timeval tv;
1493  struct timeval *ptrTv = 0;
1494  QTime stopWatch;
1495 
1496  stopWatch.start();
1497 
1498  do
1499  {
1500  fd_set readset;
1501 
1502  FD_ZERO(&readset);
1503  FD_SET(d->fd, &readset);
1504 
1505  if(-1 != msecs) {
1506  tv.tv_sec = timeout / 1000;
1507  tv.tv_usec = (timeout % 1000) * 1000;
1508  ptrTv = &tv;
1509  }
1510 
1511  int rv = ::select(d->fd + 1, &readset, 0, 0, ptrTv);
1512  switch(rv) {
1513  case 0:
1514  // timeout
1515  return false;
1516  case 1:
1517  // ok
1518  d->readActivated();
1519  return true;
1520  default:
1521  if (errno != EINTR)
1522  abort(); // error
1523  break;
1524  }
1525 
1526  timeout = msecs - stopWatch.elapsed();
1527  }
1528  while (timeout > 0);
1529 
1530  return false;
1531 }
void abort()
Abort the connection.
void start()
Sets this time to the current time.
Definition: qdatetime.cpp:2070
QUnixSocketPrivate * d
int select(int, fd_set *, fd_set *, fd_set *, struct timeval *)
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
QUnixSocket::SocketState state
The QTime class provides clock time functions.
Definition: qdatetime.h:148
int elapsed() const
Returns the number of milliseconds that have elapsed since the last time start() or restart() was cal...
Definition: qdatetime.cpp:2123
int errno

◆ write() [1/3]

qint64 QUnixSocket::write ( const char *  data,
qint64  maxSize 
)
inline

Definition at line 170 of file qunixsocket_p.h.

Referenced by writeData().

171  { return QIODevice::write(data, maxSize); }
static const char * data(const QByteArray &arr)
qint64 write(const char *data, qint64 len)
Writes at most maxSize bytes of data from data to the device.
Definition: qiodevice.cpp:1342

◆ write() [2/3]

qint64 QUnixSocket::write ( const QByteArray byteArray)
inline

Definition at line 172 of file qunixsocket_p.h.

173  { return QIODevice::write(byteArray); }
qint64 write(const char *data, qint64 len)
Writes at most maxSize bytes of data from data to the device.
Definition: qiodevice.cpp:1342

◆ write() [3/3]

qint64 QUnixSocket::write ( const QUnixSocketMessage socketdata)

Writes socketdata to the socket.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

In addition to failing if the socket is not in the Connected state, writing will fail if socketdata is QUnixSocketMessage::isValid(){invalid. }

Writes through the QUnixSocket class are asynchronous. Rather than being written immediately, data is enqueued and written once the application reenters the Qt event loop and the socket becomes available for writing. Thus, this method will only fail if the socket is not in the Connected state

  • it is illegal to attempt a write on a Unconnected or Closing socket.

Applications can monitor the progress of data writes through the QUnixSocket::bytesWritten() signal and QUnixSocket::bytesToWrite() method.

See also
QUnixSocketMessage

Definition at line 1388 of file qunixsocket.cpp.

1389 {
1390  if(ConnectedState != state() || !socketdata.isValid()) return -1;
1391  if(socketdata.d->size() == 0) return 0;
1392 
1393  d->writeQueue.enqueue(socketdata);
1394  d->writeQueueBytes += socketdata.d->size();
1395  d->writeNotifier->setEnabled(true);
1396 
1397  return socketdata.d->size();
1398 }
QUnixSocketPrivate * d
QQueue< QUnixSocketMessage > writeQueue
SocketState state() const
Returns the connection state of this instance.
unsigned int writeQueueBytes
QSharedDataPointer< QUnixSocketMessagePrivate > d
void enqueue(const T &t)
Adds value t to the tail of the queue.
Definition: qqueue.h:60
void setEnabled(bool)
If enable is true, the notifier is enabled; otherwise the notifier is disabled.
bool isValid() const
Return true if this message is valid.
QSocketNotifier * writeNotifier

◆ writeData()

qint64 QUnixSocket::writeData ( const char *  data,
qint64  maxSize 
)
protectedvirtual
Warning
This function is not part of the public interface.

Implements QIODevice.

Definition at line 1643 of file qunixsocket.cpp.

1644 {
1645  return write(QUnixSocketMessage(QByteArray(data, maxSize)));
1646 }
qint64 write(const char *data, qint64 maxSize)
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
static const char * data(const QByteArray &arr)
The QUnixSocketMessage class encapsulates a message sent or received through the QUnixSocket class...
Definition: qunixsocket_p.h:92

Properties

◆ d

QUnixSocketPrivate* QUnixSocket::d
private

The documentation for this class was generated from the following files: