-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFdObject.cpp
62 lines (55 loc) · 1.24 KB
/
FdObject.cpp
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
#include "FdObject.h"
#include <sys/stat.h>
#include <sys/mman.h>
#include <stdio.h>
AVLTree<FdObject::NodeDef> FdObject::fMap;
mutex FdObject::fMapLock = MUTEX_INITIALIZER("FdObjectMap");
FdObject::~FdObject()
{
if (fFd.IsSet()) {
MutexLocker lock(fMapLock);
fMap.Remove(this);
}
}
FdObject *FdObject::Lookup(const Key &key)
{
printf("FdObject::Lookup(%" B_PRIu64 ", %" B_PRIu64 ")\n", (uint64)key.dev, (uint64)key.ino);
// TODO: Map don't hold reference and object may reach zero reference count during call.
// It may cause return of already deleted object.
MutexLocker lock(fMapLock);
BReference<FdObject> obj(fMap.Find(key), false);
return obj.Detach();
}
int FdObject::GetFd() const
{
MutexLocker lock(fLock);
return fFd.Get();
}
int FdObject::AllocFd()
{
printf("FdObject::AllocFd()\n");
MutexLocker lock(fLock);
if (!fFd.IsSet()) {
int pipeFds[2]; // 0: read, 1: write
if (pipe(pipeFds) < 0) return -1;
close(pipeFds[1]);
SetFd(pipeFds[0]);
if (!fFd.IsSet()) return -1;
{
MutexLocker lock(fMapLock);
fMap.Insert(this);
}
}
return fFd.Get();
}
void FdObject::SetFd(int fd)
{
fFd.SetTo(fd);
struct stat st{};
if (fstat(fd, &st) < 0) {
fFd.Unset();
return;
}
fKey.dev = st.st_dev;
fKey.ino = st.st_ino;
}