blob: 7c9943d6330faee54162edd652331b52a788cac0 (
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
|
package digital.cabin.ezipc;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.platform.linux.ErrNo;
public abstract class EzIPC
{
protected interface LibraryNamedFIFO extends Library
{
static LibraryNamedFIFO INSTANCE =
Native.load("c", LibraryNamedFIFO.class);
public int mkfifo(String pathname, int mode);
}
protected LibraryNamedFIFO lib;
protected String connPath;
protected FileInputStream in_pipe;
protected FileOutputStream out_pipe;
public EzIPC(String connPath) throws IOException
{
this.lib = LibraryNamedFIFO.INSTANCE;
this.connPath = connPath;
if(lib.mkfifo(connPath+"_c2s", 0660) != 0)
if(Native.getLastError() != ErrNo.EEXIST)
throw new IOException("Could not create client->server pipe");
if(lib.mkfifo(connPath+"_s2c", 0660) != 0)
if(Native.getLastError() != ErrNo.EEXIST)
throw new IOException("Could not create server->client pipe");
this.in_pipe = null;
this.out_pipe = null;
}
public abstract void open() throws IOException;
public void close() throws IOException
{
if(in_pipe != null) in_pipe.close();
if(out_pipe != null) out_pipe.close();
}
// FIXME: check write() return val
public boolean send(byte[] data) throws IOException
{
if(out_pipe == null) return false;
if(data.length == 0) return true;
// FIXME: JAVA DOES NOT HAVE FUCKING UNSIGNED BRO
ByteBuffer bb = ByteBuffer.allocate(8);
bb.order(ByteOrder.nativeOrder()); // Imagine not being native by def.
bb.putLong(data.length);
out_pipe.write(bb.array());
out_pipe.write(data);
return true;
}
// FIXME: check write() return val
public boolean receive(byte[] data) throws IOException
{
if(in_pipe == null) return false;
if(data.length == 0) return true;
byte[] bytes = new byte[8];
// FIXME: yikes
while(in_pipe.available() < 8);
in_pipe.read(bytes);
ByteBuffer bb = ByteBuffer.wrap(bytes);
bb.order(ByteOrder.nativeOrder()); // Imagine not being native by def.
// FIXME: JAVA DOES NOT HAVE FUCKING UNSIGNED BRO
long in_size = bb.getLong();
long read_size = in_size > data.length ? data.length : in_size;
// FIXME: yikes
while(in_pipe.available() < read_size);
long read = in_pipe.read(data);
// truncate
for(long i = 0; i < (in_size - read_size); i++) in_pipe.read();
return true;
}
}
|