2020-03-24 06:22:22 +00:00
|
|
|
import Foundation
|
|
|
|
|
2022-01-02 06:54:22 +00:00
|
|
|
/// Protocol abstraction of the reading aspects of FileHandle.
|
2020-03-24 06:22:22 +00:00
|
|
|
public protocol FileHandleReader {
|
|
|
|
|
2022-01-02 06:54:22 +00:00
|
|
|
/// Gets data that is available for reading.
|
2020-03-24 06:22:22 +00:00
|
|
|
var availableData: Data { get }
|
2022-01-02 06:54:22 +00:00
|
|
|
/// A file descriptor of the handle.
|
2020-03-24 06:22:22 +00:00
|
|
|
var fileDescriptor: Int32 { get }
|
2022-01-02 06:54:22 +00:00
|
|
|
/// The process ID of the process coonnected to the other end of the FileHandle.
|
2020-03-24 06:22:22 +00:00
|
|
|
var pidOfConnectedProcess: Int32 { get }
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2022-01-02 06:54:22 +00:00
|
|
|
/// Protocol abstraction of the writing aspects of FileHandle.
|
2020-03-24 06:22:22 +00:00
|
|
|
public protocol FileHandleWriter {
|
|
|
|
|
2022-01-02 06:54:22 +00:00
|
|
|
/// Writes data to the handle.
|
2020-03-24 06:22:22 +00:00
|
|
|
func write(_ data: Data)
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
extension FileHandle: FileHandleReader, FileHandleWriter {
|
|
|
|
|
|
|
|
public var pidOfConnectedProcess: Int32 {
|
|
|
|
let pidPointer = UnsafeMutableRawPointer.allocate(byteCount: 4, alignment: 1)
|
|
|
|
var len = socklen_t(MemoryLayout<Int32>.size)
|
|
|
|
getsockopt(fileDescriptor, SOCK_STREAM, LOCAL_PEERPID, pidPointer, &len)
|
|
|
|
return pidPointer.load(as: Int32.self)
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|