1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef TESTHELPERS_H
18#define TESTHELPERS_H
19
20#include <unistd.h>
21
22#include <utils/threads.h>
23
24namespace android {
25
26class Pipe {
27public:
28    int sendFd;
29    int receiveFd;
30
31    Pipe() {
32        int fds[2];
33        ::pipe(fds);
34
35        receiveFd = fds[0];
36        sendFd = fds[1];
37    }
38
39    ~Pipe() {
40        if (sendFd != -1) {
41            ::close(sendFd);
42        }
43
44        if (receiveFd != -1) {
45            ::close(receiveFd);
46        }
47    }
48
49    status_t writeSignal() {
50        ssize_t nWritten = ::write(sendFd, "*", 1);
51        return nWritten == 1 ? 0 : -errno;
52    }
53
54    status_t readSignal() {
55        char buf[1];
56        ssize_t nRead = ::read(receiveFd, buf, 1);
57        return nRead == 1 ? 0 : nRead == 0 ? -EPIPE : -errno;
58    }
59};
60
61class DelayedTask : public Thread {
62    int mDelayMillis;
63
64public:
65    DelayedTask(int delayMillis) : mDelayMillis(delayMillis) { }
66
67protected:
68    virtual ~DelayedTask() { }
69
70    virtual void doTask() = 0;
71
72    virtual bool threadLoop() {
73        usleep(mDelayMillis * 1000);
74        doTask();
75        return false;
76    }
77};
78
79} // namespace android
80
81#endif // TESTHELPERS_H
82