~ci-train-bot/location-service/location-service-ubuntu-yakkety-1895

« back to all changes in this revision

Viewing changes to tests/fork_and_run.h

  • Committer: Thomas Voß
  • Date: 2013-05-28 14:20:45 UTC
  • Revision ID: thomas.voss@canonical.com-20130528142045-kq5umqdmm4o53vwk
Initial push.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#ifndef FORK_AND_RUN_H_
 
2
#define FORK_AND_RUN_H_
 
3
 
 
4
#include <cstring>
 
5
#include <functional>
 
6
#include <stdexcept>
 
7
 
 
8
#include <sys/types.h>
 
9
#include <signal.h>
 
10
#include <unistd.h>
 
11
 
 
12
namespace test
 
13
{
 
14
bool is_child(pid_t pid)
 
15
{
 
16
    return pid == 0;
 
17
}
 
18
 
 
19
int fork_and_run(std::function<void()> child, std::function<void()> parent)
 
20
{
 
21
    auto pid = fork();
 
22
 
 
23
    if (pid < 0)
 
24
    {
 
25
        throw std::runtime_error(std::string("Could not fork child: ") + std::strerror(errno));
 
26
    }
 
27
 
 
28
    if (is_child(pid))
 
29
    {
 
30
        child();
 
31
        return EXIT_SUCCESS;
 
32
    }
 
33
    else
 
34
    {
 
35
        parent();
 
36
        kill(pid, SIGKILL);
 
37
        return EXIT_SUCCESS;
 
38
    }
 
39
 
 
40
    return EXIT_FAILURE;
 
41
}
 
42
}
 
43
 
 
44
#endif // FORK_AND_RUN_H_