Initial work

This commit is contained in:
Simon Fels 2016-05-26 22:38:57 +02:00 committed by Simon Fels
commit 3222551702
374 changed files with 40290 additions and 0 deletions

View file

@ -0,0 +1,39 @@
# Copyright © 2013 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Authored by: Thomas Voss <thomas.voss@canonical.com>
cmake_minimum_required(VERSION 2.8)
project(process-cpp)
find_package(Boost COMPONENTS iostreams system REQUIRED)
find_package(Threads REQUIRED)
include(GNUInstallDirs)
set(PROCESS_CPP_VERSION_MAJOR 2)
set(PROCESS_CPP_VERSION_MINOR 0)
set(PROCESS_CPP_VERSION_PATCH 0)
include(CTest)
include_directories(
include/
src/
external/process-cpp-minimal
${Boost_INCLUDE_DIRS}
)
add_subdirectory(src)

165
external/process-cpp-minimal/COPYING vendored Normal file
View file

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

86
external/process-cpp-minimal/README.md vendored Normal file
View file

@ -0,0 +1,86 @@
process-cpp {#mainpage}
===========
process-cpp is a simple and straightforward wrapper around process creation and
control targeted towards linux. It helps both with handling child processes and with
interacting with the current process. Some of its features include:
- Thread-safe get/set/unset operation on the current process's environment.
- Throwing and non-throwing overloads of functions when system calls are involved.
- Seamless redirection of input, output and error streams of child processes.
- Type-safe interaction with the virtual proc filesystem, both for reading & writing.
The library's main purpose is to assist in testing and when a software component
needs to carry out process creation/control tasks, e.g., a graphical shell. To this end,
the library is extensively tested and tries to ensure fail-safe operation as much as possible.
A simple echo
-------------
~~~~~~~~~~~~~{.cpp}
// Fork and run a simple echo:
posix::ChildProcess child = posix::fork(
[]()
{
std::string line;
while(true)
{
std::cin >> line;
std::cout << line << std::endl;
}
return EXIT_FAILURE;
},
posix::StandardStreamFlags()
.set(posix::StandardStream::stdin)
.set(posix::StandardStream::stdout));
// Check that the resulting process has a valid pid.
EXPECT_TRUE(child.pid() > 0);
// Check on echo functionality.
const std::string echo_value{"42"};
child.cin() << echo_value << std::endl;
std::string line; child.cout() >> line;
EXPECT_EQ(echo_value, line);
// Stop the process and synchronize with the process changing state.
EXPECT_NO_THROW(child.send_signal(posix::Signal::sig_stop));
auto result = child.wait_for(posix::wait::Flag::untraced);
EXPECT_EQ(posix::wait::Result::Status::stopped,
result.status);
EXPECT_EQ(posix::Signal::sig_stop,
result.detail.if_stopped.signal);
// Kill the stopped process and synchronize to its state change.
EXPECT_NO_THROW(child.send_signal(posix::Signal::sig_kill));
result = child.wait_for(posix::wait::Flag::untraced);
EXPECT_EQ(posix::wait::Result::Status::signaled,
result.status);
EXPECT_EQ(posix::Signal::sig_kill,
result.detail.if_signaled.signal);
~~~~~~~~~~~~~
Adjusting OOM Score Values
--------------------------
~~~~~~~~~~~~~{.cpp}
// Setup the manipulator with a well-known value.
posix::linux::proc::process::OomScoreAdj oom_score_adj
{
posix::linux::proc::process::OomScoreAdj::max_value()
};
// Apply the manipulator to the current process
EXPECT_NO_THROW(posix::this_process::instance() << oom_score_adj);
// Read back the manipulators value for the current process
EXPECT_NO_THROW(posix::this_process::instance() >> oom_score_adj);
// And check that applying the manipulator was successful.
EXPECT_EQ(posix::linux::proc::process::OomScoreAdj::max_value(),
oom_score_adj.value);
// Instantiate the observer...
posix::linux::proc::process::OomScore oom_score;
// ... and fill in its value for the current process.
EXPECT_NO_THROW(posix::this_process::instance() >> oom_score);
// Check that applying the manipulator before results in adjustments to the
// OOM score.
EXPECT_TRUE(is_approximately_equal(oom_score.value, posix::linux::proc::process::OomScoreAdj::max_value()));
~~~~~~~~~~~~~

View file

@ -0,0 +1,190 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef COM_UBUNTU_CONNECTION_H_
#define COM_UBUNTU_CONNECTION_H_
#include <functional>
#include <memory>
#include <mutex>
namespace core
{
class ScopedConnection;
/**
* @brief The Connection class models a signal-slot connection.
*/
class Connection
{
public:
typedef std::function<void(const std::function<void()>&)> Dispatcher;
/**
* @brief Checks if this instance corresponds to an active signal-slot connection.
* @return true iff the instance corresponds to an active signal-slot connection.
*/
inline bool is_connected() const
{
if (!d)
return false;
return (d->disconnector ? true : false);
}
/**
* @brief End a signal-slot connection.
*/
inline void disconnect()
{
if (d)
d->disconnect();
}
/**
* @brief Installs a dispatcher for this signal-slot connection.
* @param dispatcher The dispatcher to be used for signal emissions.
*/
inline void dispatch_via(const Dispatcher& dispatcher)
{
if (d && d->dispatcher_installer)
d->dispatcher_installer(dispatcher);
}
private:
friend class ScopedConnection;
typedef std::function<void()> Disconnector;
typedef std::function<void(const Dispatcher&)> DispatcherInstaller;
template<typename ... Arguments> friend class Signal;
inline Connection(const Disconnector& disconnector,
const DispatcherInstaller& installer)
: d(std::make_shared<Private>(disconnector, installer))
{
}
inline bool operator<(const Connection& rhs) const
{
return d < rhs.d;
}
inline void reset()
{
if (d)
d->reset();
}
struct Private
{
Private(const Connection::Disconnector& disconnector,
const Connection::DispatcherInstaller& dispatcher_installer)
: disconnector(disconnector),
dispatcher_installer(dispatcher_installer)
{
}
inline void reset()
{
std::lock_guard<std::mutex> lg(guard);
reset_locked();
}
inline void reset_locked()
{
static const Connection::Disconnector empty_disconnector{};
static const Connection::DispatcherInstaller empty_dispatcher_installer{};
disconnector = empty_disconnector;
dispatcher_installer = empty_dispatcher_installer;
}
inline void disconnect()
{
static const Connection::Disconnector empty_disconnector{};
std::lock_guard<std::mutex> lg(guard);
if (disconnector)
disconnector();
reset_locked();
}
std::mutex guard;
Connection::Disconnector disconnector;
Connection::DispatcherInstaller dispatcher_installer;
};
// The whole class is implicitly shared and we thus forward our complete
// shared state to a private structure that is lifetime-managed by a shared_ptr.
std::shared_ptr<Private> d;
};
/**
* @brief Scoped helper class to map signal-slot connection mgmt. to RAII.
*/
class ScopedConnection
{
public:
/**
* @brief Constructs an instance for an existing signal-slot connection.
* @param c The existing signal-slot connection.
*/
inline ScopedConnection(const Connection& c) : connection(c)
{
}
inline ScopedConnection(ScopedConnection&& rhs) : connection(std::move(rhs.connection))
{
}
ScopedConnection(const ScopedConnection&) = delete;
/**
* @brief Disconnects the signal-slot connection.
*/
inline ~ScopedConnection() noexcept(true)
{
try
{
connection.disconnect();
} catch(...)
{
}
}
inline ScopedConnection& operator=(ScopedConnection&& rhs)
{
connection = std::move(rhs.connection);
return *this;
}
ScopedConnection& operator=(const ScopedConnection&) = delete;
bool operator==(const ScopedConnection&) = delete;
inline bool operator<(const ScopedConnection& rhs) const
{
return connection < rhs.connection;
}
private:
Connection connection;
};
}
#endif // COM_UBUNTU_CONNECTION_H_

View file

@ -0,0 +1,169 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef CORE_POSIX_CHILD_PROCESS_H_
#define CORE_POSIX_CHILD_PROCESS_H_
#include <core/posix/process.h>
#include <core/posix/standard_stream.h>
#include <core/posix/visibility.h>
#include <core/signal.h>
#include <iosfwd>
#include <functional>
namespace core
{
namespace posix
{
/**
* @brief The Process class models a child process of this process.
*
* In addition to the functionality offered by the Process class, an instance
* of ChildProcess offers functionality to wait for status changes of the child
* process and to access the child process's standard streams if they have been
* redirected when forking or exec'ing.
*/
class CORE_POSIX_DLL_PUBLIC ChildProcess : public Process
{
public:
/**
* @brief The DeathObserver class observes child process' states and emits a signal when a monitored child has died.
*
* Please note that the name of this class is morbid for a reason: Listening
* for SIGCHLD is not enough to catch all dying children. Whenever a SIGCHLD is
* received, we have to wait for all the children of this process and reap all
* monitored ones. We are thus changing state and potentially race with other
* wait operations on children.
*
*/
class DeathObserver
{
public:
/**
* @brief Creates the unique instance of class DeathObserver.
* @throw std::logic_error if the given SignalTrap instance does not trap Signal::sig_chld.
* @throw std::runtime_error if there already is an instance of the death observer.
*/
static std::unique_ptr<DeathObserver> create_once_with_signal_trap(
std::shared_ptr<SignalTrap> trap);
DeathObserver(const DeathObserver&) = delete;
virtual ~DeathObserver() = default;
DeathObserver& operator=(const DeathObserver&) = delete;
bool operator==(const DeathObserver&) const = delete;
/**
* @brief add adds the specified child to the list of observed child processes.
* @param child The child to be observed.
* @return true iff the child has been added to the list of observed child processes.
*/
virtual bool add(const ChildProcess& child) = 0;
/**
* @brief has checks whether the specified child is observed.
* @param child The child to check for.
* @return true iff the specified child is observed for state changes.
*/
virtual bool has(const ChildProcess& child) const = 0;
/**
* @brief child_died is emitted whenever an observed child ceases to exist.
*/
virtual const core::Signal<ChildProcess>& child_died() const = 0;
/**
* @brief Checks and reaps all child processes registered with the observer instance.
*/
virtual void on_sig_child() = 0;
protected:
DeathObserver() = default;
};
/**
* @brief Creates an invalid ChildProcess.
* @return An invalid ChildProcess instance.
*/
static ChildProcess invalid();
~ChildProcess();
/**
* @brief Wait for the child process to change state.
* @param [in] flags Alters the behavior of the wait operation.
* @return Result of the wait operation, as well as information about the
* reasons for a child process's state change.
*/
wait::Result wait_for(const wait::Flags& flags);
/**
* @brief Access this process's stderr.
*/
std::istream& cerr();
/**
* @brief Access this process's stdin.
*/
std::ostream& cin();
/**
* @brief Access this process's stdout.
*/
std::istream& cout();
private:
friend ChildProcess fork(const std::function<posix::exit::Status()>&, const StandardStream&);
friend ChildProcess vfork(const std::function<posix::exit::Status()>&, const StandardStream&);
class CORE_POSIX_DLL_LOCAL Pipe
{
public:
static Pipe invalid();
Pipe();
Pipe(const Pipe& rhs);
~Pipe();
Pipe& operator=(const Pipe& rhs);
int read_fd() const;
void close_read_fd();
int write_fd() const;
void close_write_fd();
private:
Pipe(int fds[2]);
int fds[2];
};
CORE_POSIX_DLL_LOCAL ChildProcess(pid_t pid,
const Pipe& stdin,
const Pipe& stdout,
const Pipe& stderr);
struct CORE_POSIX_DLL_LOCAL Private;
std::shared_ptr<Private> d;
};
}
}
#endif // CORE_POSIX_CHILD_PROCESS_H_

View file

@ -0,0 +1,68 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef CORE_POSIX_EXEC_H_
#define CORE_POSIX_EXEC_H_
#include <core/posix/child_process.h>
#include <core/posix/visibility.h>
#include <functional>
#include <map>
#include <string>
#include <vector>
namespace core
{
namespace posix
{
enum class RedirectFlags;
/**
* @brief exec execve's the executable with the provided arguments and environment.
* @throws std::system_error in case of errors.
* @param fn The executable to run.
* @param argv Vector of command line arguments
* @param env Environment that the new process should run under
* @param flags Specifies which standard streams should be redirected.
* @return An instance of ChildProcess corresponding to the newly exec'd process.
*/
CORE_POSIX_DLL_PUBLIC ChildProcess exec(const std::string& fn,
const std::vector<std::string>& argv,
const std::map<std::string, std::string>& env,
const StandardStream& flags);
/**
* @brief exec execve's the executable with the provided arguments and environment.
* @throws std::system_error in case of errors.
* @param fn The executable to run.
* @param argv Vector of command line arguments
* @param env Environment that the new process should run under
* @param flags Specifies which standard streams should be redirected.
* @param child_setup Function to run in the child just before exec().
* @return An instance of ChildProcess corresponding to the newly exec'd process.
*/
CORE_POSIX_DLL_PUBLIC ChildProcess exec(const std::string& fn,
const std::vector<std::string>& argv,
const std::map<std::string, std::string>& env,
const StandardStream& flags,
const std::function<void()>& child_setup);
}
}
#endif // CORE_POSIX_EXEC_H_

View file

@ -0,0 +1,42 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef CORE_POSIX_EXIT_H_
#define CORE_POSIX_EXIT_H_
#include <cstdlib>
namespace core
{
namespace posix
{
namespace exit
{
/**
* @brief The Status enum wrap's the posix exit status.
*/
enum class Status
{
success = EXIT_SUCCESS,
failure = EXIT_FAILURE
};
}
}
}
#endif // CORE_POSIX_EXIT_H_

View file

@ -0,0 +1,54 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef CORE_POSIX_FORK_H_
#define CORE_POSIX_FORK_H_
#include <core/posix/child_process.h>
#include <core/posix/standard_stream.h>
#include <core/posix/visibility.h>
#include <functional>
namespace core
{
namespace posix
{
/**
* @brief fork forks a new process and executes the provided main function in the newly forked process.
* @throws std::system_error in case of errors.
* @param [in] main The main function of the newly forked process.
* @param [in] flags Specify which standard streams should be redirected to the parent process.
* @return An instance of ChildProcess in case of success.
*/
CORE_POSIX_DLL_PUBLIC ChildProcess fork(const std::function<posix::exit::Status()>& main,
const StandardStream& flags);
/**
* @brief fork vforks a new process and executes the provided main function in the newly forked process.
* @throws std::system_error in case of errors.
* @param [in] main The main function of the newly forked process.
* @param [in] flags Specify which standard streams should be redirected to the parent process.
* @return An instance of ChildProcess in case of success.
*/
CORE_POSIX_DLL_PUBLIC ChildProcess vfork(const std::function<posix::exit::Status()>& main,
const StandardStream& flags);
}
}
#endif // CORE_POSIX_FORK_H_

View file

@ -0,0 +1,106 @@
/*
* Copyright © 2012-2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef CORE_POSIX_LINUX_PROC_PROCESS_OOM_ADJ_H_
#define CORE_POSIX_LINUX_PROC_PROCESS_OOM_ADJ_H_
#include <core/posix/visibility.h>
namespace core
{
namespace posix
{
class Process;
namespace linux
{
namespace proc
{
namespace process
{
/**
* This file can be used to adjust the score used to select which process
* should be killed in an out-of-memory (OOM) situation. The kernel uses this
* value for a bit-shift operation of the process's oom_score value: valid
* values are in the range -16 to +15, plus the special value -17, which disables
* OOM-killing altogether for this process. A positive score increases the
* likelihood of this process being killed by the OOM-killer; a negative score
* decreases the likelihood.
*
* The default value for this file is 0; a new process inherits its parent's
* oom_adj setting. A process must be privileged (CAP_SYS_RESOURCE) to update
* this file.
*
* Since Linux 2.6.36, use of this file is deprecated in favor of
* /proc/[pid]/oom_score_adj.
*/
struct CORE_POSIX_DLL_PUBLIC OomAdj
{
/**
* @brief Returns the value that makes a process "invisible" to the oom killer.
* @return Returns the value that makes a process "invisible" to the oom killer.
*/
static int disable_value();
/**
* @brief Returns the minimum valid value.
* @return The minimum valid value that the OomAdj can be set to.
*/
static int min_value();
/**
* @brief Returns the maximum valid value.
* @return The maximum valid value that the OomAdj can be set to.
*/
static int max_value();
/**
* @brief is_valid checks whether the contained value is within the predefined bounds.
* @return true iff min_value() <= value <= max_value().
*/
inline bool is_valid() const
{
return (disable_value() <= value) && (value <= max_value());
}
/**
* @brief Current value.
*/
int value;
};
/**
* \brief Read the OomAdj value for a process instance.
* \throws std::runtime_error in case of errors.
* \param [in] process The process to read the score for.
* \param [out] adj The destination to store the value in.
*/
CORE_POSIX_DLL_PUBLIC const posix::Process& operator>>(const posix::Process& process, OomAdj& adj);
/**
* \brief Write the OomAdj value for a process instance.
* \throw std::runtime_error in case of errors and std::logic_error if score_adj.is_valid() returns false.
* \param [in] process The process to write the score for.
* \param [in] adj The new value to store.
*/
CORE_POSIX_DLL_PUBLIC const posix::Process& operator<<(const posix::Process& process,
const OomAdj& adj);
}
}
}
}
}
#endif // CORE_POSIX_LINUX_PROC_PROCESS_OOM_ADJ_H_

View file

@ -0,0 +1,67 @@
/*
* Copyright © 2012-2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef CORE_POSIX_LINUX_PROC_PROCESS_OOM_SCORE_H_
#define CORE_POSIX_LINUX_PROC_PROCESS_OOM_SCORE_H_
#include <core/posix/visibility.h>
namespace core
{
namespace posix
{
class Process;
namespace linux
{
namespace proc
{
namespace process
{
/**
* This file displays the current score that the kernel gives to this process
* for the purpose of selecting a process for the OOM-killer. A higher score
* means that the process is more likely to be selected by the OOM-killer. The
* basis for this score is the amount of memory used by the process, with
* increases (+) or decreases (-) for factors including:
*
* - whether the process creates a lot of children using fork(2) (+);
* - whether the process has been running a long time, or has used a lot of CPU time (-);
* - whether the process has a low nice value (i.e., > 0) (+);
* - whether the process is privileged (-); and
* - whether the process is making direct hardware access (-).
*
* The oom_score also reflects the adjustment specified by the oom_score_adj or
* oom_adj setting for the process.
*/
struct CORE_POSIX_DLL_PUBLIC OomScore
{
int value = 0; ///< Current OomScore as calculated by the kernel.
};
/**
* \brief Read the OomScore for a process instance.
* \throws std::runtime_error in case of errors.
* \param [in] process The process to read the score for.
* \param [out] score The destination to store the value in.
*/
CORE_POSIX_DLL_PUBLIC const posix::Process& operator>>(const posix::Process& process, OomScore& score);
}
}
}
}
}
#endif // CORE_POSIX_LINUX_PROC_PROCESS_OOM_SCORE_H_

View file

@ -0,0 +1,131 @@
/*
* Copyright © 2012-2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef CORE_POSIX_LINUX_PROC_PROCESS_OOM_SCORE_ADJ_H_
#define CORE_POSIX_LINUX_PROC_PROCESS_OOM_SCORE_ADJ_H_
#include <core/posix/visibility.h>
namespace core
{
namespace posix
{
class Process;
namespace linux
{
namespace proc
{
namespace process
{
/**
* This file can be used to adjust the badness heuristic used to select which
* process gets killed in out-of-memory conditions.
*
* The badness heuristic assigns a value to each candidate task ranging from 0
* (never kill) to 1000 (always kill) to determine which process is targeted.
* The units are roughly a proportion along that range of allowed memory the
* process may allocate from, based on an estimation of its current memory and
* swap use. For example, if a task is using all allowed memory, its badness
* score will be 1000. If it is using half of its allowed memory, its score
* will be 500.
*
* There is an additional factor included in the badness score: root processes are
* given 3% extra memory over other tasks.
*
* The amount of "allowed" memory depends on the context in which the
* OOM-killer was called. If it is due to the memory assigned to the allocating
* task's cpuset being exhausted, the allowed memory represents the set of mems
* assigned to that cpuset (see cpuset(7)). If it is due to a mempolicy's node(s)
* being exhausted, the allowed memory represents the set of mempolicy nodes. If
* it is due to a memory limit (or swap limit) being reached, the allowed memory
* is that configured limit. Finally, if it is due to the entire system being out
* of memory, the allowed memory represents all allocatable resources.
*
* The value of oom_score_adj is added to the badness score before it is used
* to determine which task to kill. Acceptable values range from -1000
* (OOM_SCORE_ADJ_MIN) to +1000 (OOM_SCORE_ADJ_MAX). This allows user space to
* control the preference for OOM-killing, ranging from always preferring a
* certain task or completely disabling it from OOM- killing. The lowest possible
* value, -1000, is equivalent to disabling OOM-killing entirely for that task,
* since it will always report a badness score of 0.
*
* Consequently, it is very simple for user space to define the amount of
* memory to consider for each task. Setting a oom_score_adj value of +500, for
* example, is roughly equivalent to allowing the remainder of tasks sharing
* the same system, cpuset, mempolicy, or memory controller resources to use at
* least 50% more memory. A value of -500, on the other hand, would be roughly
* equivalent to discounting 50% of the task's allowed memory from being
* considered as scoring against the task.
*
* For backward compatibility with previous kernels, /proc/[pid]/oom_adj can
* still be used to tune the badness score. Its value is scaled linearly with
* oom_score_adj.
*
* Writing to /proc/[pid]/oom_score_adj or /proc/[pid]/oom_adj will change the
* other with its scaled value.
*/
struct CORE_POSIX_DLL_PUBLIC OomScoreAdj
{
/**
* @brief Returns the minimum valid value.
* @return The minimum valid value that the Oom Score Adj can be set to.
*/
static int min_value();
/**
* @brief Returns the maximum valid value.
* @return The maximum valid value that the Oom Score Adj can be set to.
*/
static int max_value();
/**
* @brief is_valid checks whether the contained value is within the predefined bounds.
* @return true iff min_value() <= value <= max_value().
*/
inline bool is_valid() const
{
return (min_value() <= value) && (value <= max_value());
}
/**
* @brief Current value.
*/
int value;
};
/**
* @brief Read the OomScoreAdj value for a process instance.
* @throw std::runtime_error in case of errors.
* @param [in] process The process to read the score for.
* @param [out] score_adj The destination to store the value in.
*/
CORE_POSIX_DLL_PUBLIC const posix::Process& operator>>(const posix::Process& process, OomScoreAdj& score_adj);
/**
* @brief Write the OomScoreAdj value for a process instance.
* @throw std::runtime_error in case of errors and std::logic_error if score_adj.is_valid() returns false.
* @param [in] process The process to write the score for.
* @param [in] score_adj The new value to store.
*/
CORE_POSIX_DLL_PUBLIC const posix::Process& operator<<(const posix::Process& process,
const OomScoreAdj& score_adj);
}
}
}
}
}
#endif // CORE_POSIX_LINUX_PROC_PROCESS_OOM_SCORE_ADJ_H_

View file

@ -0,0 +1,120 @@
/*
* Copyright © 2012-2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef CORE_POSIX_LINUX_PROC_PROCESS_STAT_H_
#define CORE_POSIX_LINUX_PROC_PROCESS_STAT_H_
#include <core/posix/linux/proc/process/state.h>
#include <core/posix/visibility.h>
#include <string>
namespace core
{
namespace posix
{
class Process;
namespace linux
{
namespace proc
{
namespace process
{
/**
* @brief The Stat struct encapsulates status information about a process.
*/
struct CORE_POSIX_DLL_PUBLIC Stat
{
pid_t pid = 1; ///< The process ID
std::string executable; ///< The filename of the executable, in parentheses.
State state = State::undefined; ///< State of the process.
pid_t parent = -1; ///< The PID of the parent.
pid_t process_group = -1; ///< The process group ID of the process.
int session_id = -1; ///< The session ID of the process.
int tty_nr = -1; ///< The controlling terminal of the process.
int controlling_process_group = -1; ///< The ID of the foreground process group of the controlling terminal of the process.
unsigned int kernel_flags = 0; ///< The kernel flags word of the process.
long unsigned int minor_faults_count = 0; ///< The number of minor faults the process has made which have not required loading a memory page from disk.
long unsigned int minor_faults_count_by_children = 0; ///< The number of minor faults that the process's waited-for children have made.
long unsigned int major_faults_count = 0; ///< The number of major faults the process has made which have required loading a memory page from disk.
long unsigned int major_faults_count_by_children = 0; ///< The number of major faults that the process's waited-for children have made.
struct
{
long unsigned int user = 0; ///< Amount of time that this process has been scheduled in user mode, [clock ticks].
long unsigned int system = 0; ///< Amount of time that this process has been scheduled in kernel mode, [clock ticks].
long unsigned int user_for_children = 0; ///< Amount of time that this process's waited-for children have been scheduled in user mode, [clock ticks].
long unsigned int system_for_children = 0; ///< Amount of time that this process's waited-for children have been scheduled in kernel mode, [clock ticks].
} time;
/**
* (Explanation for Linux 2.6) For processes running a real-time scheduling
* policy (policy below; see sched_setscheduler(2)), this is the negated
* scheduling priority, minus one; that is, a number in the range -2 to
* -100, corresponding to real-time priorities 1 to 99. For processes running
* under a non-real-time scheduling policy, this is the raw nice value
* (setpriority(2)) as represented in the kernel. The kernel stores nice
* values as numbers in the range 0 (high) to 39 (low), corresponding to
* the user-visible nice range of -20 to 19.
*
*Before Linux 2.6, this was a scaled value based on the scheduler
*weighting given to this process.
*/
long int priority = 0;
long int nice = 0; ///< The nice value (see setpriority(2)), a value in the range 19 (low priority) to -20 (high priority).
long int thread_count = 0; ///< Number of threads in this process (since Linux 2.6).
long int time_before_next_sig_alarm = 0; ///< The time in jiffies before the next SIGALRM is sent to the process due to an interval timer. Since kernel 2.6.17, this field is no longer maintained, and is hard coded as 0.
long int start_time = 0; ///< The time the process started after system boot. In kernels before Linux 2.6, this value was expressed in jiffies. Since Linux 2.6, the value is expressed in clock ticks (divide by sysconf(_SC_CLK_TCK)).
struct
{
long unsigned int virt = 0; ///< Virtual memory size in bytes.
long unsigned int resident_set = 0; ///< Resident Set Size: number of pages the process has in real memory. This is just the pages which count toward text, data, or stack space. This does not include pages which have not been demand-loaded in, or which are swapped out.
long unsigned int resident_set_limit = 0; ///< Current soft limit in bytes on the rss of the process; see the description of RLIMIT_RSS in getrlimit(2).
} size;
struct
{
long unsigned int start_code = 0; ///< The address above which program text can run.
long unsigned int end_code = 0; ///< The address below which program text can run.
long unsigned int start_stack = 0; ///< The address of the start (i.e., bottom) of the stack.
long unsigned int stack_pointer = 0; ///< The current value of ESP (stack pointer), as found in the kernel stack page for the process.
long unsigned int instruction_pointer = 0; ///< The current EIP (instruction pointer).
} addresses;
struct
{
long unsigned int pending = 0; ///< The bitmap of pending signals, displayed as a decimal number. Obsolete, because it does not provide information on real-time signals; use /proc/[pid]/status instead.
long unsigned int blocked = 0; ///< The bitmap of blocked signals, displayed as a decimal number. Obsolete, because it does not provide information on real-time signals; use /proc/[pid]/status instead.
long unsigned int ignored = 0; ///< The bitmap of ignored signals, displayed as a decimal number. Obsolete, because it does not provide information on real-time signals; use /proc/[pid]/status instead.
long unsigned int caught = 0; ///< The bitmap of caught signals, displayed as a decimal number. Obsolete, because it does not provide information on real-time signals; use /proc/[pid]/status instead.
} signals;
long unsigned int channel = 0; ///< This is the "channel" in which the process is waiting. It is the address of a system call, and can be looked up in a namelist if you need a textual name. (If you have an up-to-date /etc/psdatabase, then try ps -l to see the WCHAN field in action.)
long unsigned int swap_count = 0; ///< Number of pages swapped (not maintained).
long unsigned int swap_count_children = 0; ///< Cumulative nswap for child processes (not maintained).
int exit_signal = -1; ///< Signal to be sent to parent when we die.
int cpu_count = -1; ///< CPU number last executed on.
unsigned int realtime_priority = 0; ///< Real-time scheduling priority, a number in the range 1 to 99 for processes scheduled under a real-time policy, or 0, for non-real-time processes (see sched_setscheduler(2)).
unsigned int scheduling_policy = 0; ///< Scheduling policy (see sched_setscheduler(2)). Decode using the SCHED_* constants in linux/sched.h.
long long unsigned int aggregated_block_io_delays = 0; ///< Aggregated block I/O delays, measured in clock ticks (centiseconds).
long unsigned int guest_time = 0; ///< Guest time of the process (time spent running a virtual CPU for a guest operating system), measured in clock ticks.
long unsigned int guest_time_children = 0; ///< Guest time of the process's children, measured in clock ticks.
};
CORE_POSIX_DLL_PUBLIC const posix::Process& operator>>(const posix::Process& process, Stat& stat);
}
}
}
}
}
#endif // CORE_POSIX_LINUX_PROC_PROCESS_STAT_H_

View file

@ -0,0 +1,51 @@
/*
* Copyright © 2012-2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef CORE_POSIX_LINUX_PROC_PROCESS_STATE_H_
#define CORE_POSIX_LINUX_PROC_PROCESS_STATE_H_
#include <core/posix/visibility.h>
#include <iosfwd>
namespace core
{
namespace posix
{
namespace linux
{
namespace proc
{
namespace process
{
enum class State
{
undefined = -1,
running = 'R',
sleeping = 'S',
disk_sleep = 'D',
zombie = 'Z',
traced_or_stopped = 'T',
paging = 'W'
};
}
}
}
}
}
#endif // CORE_POSIX_LINUX_PROC_PROCESS_STATE_H_

View file

@ -0,0 +1,93 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef CORE_POSIX_PROCESS_H_
#define CORE_POSIX_PROCESS_H_
#include <core/posix/process_group.h>
#include <core/posix/signalable.h>
#include <core/posix/this_process.h>
#include <core/posix/visibility.h>
#include <core/posix/wait.h>
#include <memory>
#include <system_error>
namespace core
{
namespace posix
{
enum class Signal;
class Self;
class WaitFlags;
/**
* @brief The Process class models a process and possible operations on it.
*
* The process class is implicitly shared.
*/
class CORE_POSIX_DLL_PUBLIC Process : public Signalable
{
public:
/**
* @brief Creates a process instance wrapping an existing process.
* @throw Throw std::system_error if pid is invalid, i.e., pid < 0.
* @param pid The process identifier of the existing process.
*/
explicit Process(pid_t pid);
/**
* @brief Returns an invalid instance for testing purposes.
* @return An invalid instance.
*/
static Process invalid();
/**
* @brief Frees resources associated with the process.
*/
virtual ~Process() noexcept;
/**
* @brief Query the pid of the process.
* @return The pid of the process.
*/
virtual pid_t pid() const;
/**
* @brief Queries the id of the process group this process belongs to.
* @throw std::system_error in case of errors.
* @return The id of the process group this process belongs to.
*/
virtual ProcessGroup process_group_or_throw() const;
/**
* @brief Queries the id of the process group this process belongs to.
*
* @return A tuple with the first element being the id of the process group
* this process belongs to and the second element a boolean flag indicating
* an error if true.
*/
virtual ProcessGroup process_group(std::error_code& se) const noexcept(true);
private:
struct CORE_POSIX_DLL_LOCAL Private;
std::shared_ptr<Private> d;
};
}
}
#endif // CORE_POSIX_PROCESS_H_

View file

@ -0,0 +1,65 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef CORE_POSIX_PROCESS_GROUP_H_
#define CORE_POSIX_PROCESS_GROUP_H_
#include <core/posix/signalable.h>
#include <core/posix/visibility.h>
#include <memory>
namespace core
{
namespace posix
{
class Process;
/**
* @brief The ProcessGroup class models a signalable group of process.
*
* Summary from http://en.wikipedia.org/wiki/Process_group:
*
* In POSIX-conformant operating systems, a process group denotes a collection
* of one or more processes. Process groups are used to control the distribution
* of signals. A signal directed to a process group is delivered individually to
* all of the processes that are members of the group.
*/
class CORE_POSIX_DLL_PUBLIC ProcessGroup : public Signalable
{
public:
/**
* @brief Accesses the id of this process group.
* @return The id of this process group.
*/
virtual pid_t id() const;
static ProcessGroup invalid();
protected:
friend class Process;
CORE_POSIX_DLL_LOCAL ProcessGroup(pid_t id);
private:
struct CORE_POSIX_DLL_LOCAL Private;
std::shared_ptr<Private> d;
};
}
}
#endif // CORE_POSIX_PROCESS_GROUP_H_

View file

@ -0,0 +1,117 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef CORE_POSIX_SIGNAL_H_
#define CORE_POSIX_SIGNAL_H_
#include <core/posix/visibility.h>
#include <core/signal.h>
#include <signal.h>
#include <initializer_list>
#include <memory>
namespace core
{
namespace posix
{
/**
* @brief The Signal enum collects the most common POSIX signals.
*/
enum class Signal
{
unknown = 0,
sig_hup = SIGHUP,
sig_int = SIGINT,
sig_quit = SIGQUIT,
sig_ill = SIGILL,
sig_abrt = SIGABRT,
sig_fpe = SIGFPE,
sig_kill = SIGKILL,
sig_segv = SIGSEGV,
sig_pipe = SIGPIPE,
sig_alrm = SIGALRM,
sig_term = SIGTERM,
sig_usr1 = SIGUSR1,
sig_usr2 = SIGUSR2,
sig_chld = SIGCHLD,
sig_cont = SIGCONT,
sig_stop = SIGSTOP,
sig_tstp = SIGTSTP,
sig_ttin = SIGTTIN,
sig_ttou = SIGTTOU
};
/**
* @brief The SignalTrap class encapsulates functionality to trap and handle signals.
*/
class CORE_POSIX_DLL_PUBLIC SignalTrap
{
public:
SignalTrap(const SignalTrap&) = delete;
virtual ~SignalTrap() = default;
SignalTrap& operator=(const SignalTrap&) = delete;
bool operator==(const SignalTrap&) const = delete;
/**
* @brief Returns true if the given signal is trapped by this instance.
*/
virtual bool has(Signal signal) = 0;
/**
* @brief Starts observation of incoming signals, relaying them via
* signal_raised(). The call blocks until stop is called.
*/
virtual void run() = 0;
/**
* @brief Stops execution of the signal trap.
*/
virtual void stop() = 0;
/**
* @brief Emitted whenever a trapped signal is raised by the operating system.
*/
virtual core::Signal<Signal>& signal_raised() = 0;
protected:
SignalTrap() = default;
};
/**
* @brief Traps the specified signals for the entire process.
*/
CORE_POSIX_DLL_PUBLIC
std::shared_ptr<SignalTrap> trap_signals_for_process(
std::initializer_list<core::posix::Signal> blocked_signals);
/**
* @brief Traps the specified signals for the current thread, and inherits
* the respective signal mask to all child-threads.
*/
CORE_POSIX_DLL_PUBLIC
std::shared_ptr<SignalTrap> trap_signals_for_all_subsequent_threads(
std::initializer_list<core::posix::Signal> blocked_signals);
}
}
#endif

View file

@ -0,0 +1,64 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef CORE_POSIX_SIGNALABLE_H_
#define CORE_POSIX_SIGNALABLE_H_
#include <core/posix/signal.h>
#include <core/posix/visibility.h>
#include <memory>
#include <system_error>
namespace core
{
namespace posix
{
/**
* @brief The Signalable class abstracts the ability of an entity to be delivered a posix signal.
*/
class CORE_POSIX_DLL_PUBLIC Signalable
{
public:
virtual ~Signalable() { }
/**
* @brief Sends a signal to this signalable object.
* @throws std::system_error in case of problems.
* @param [in] signal The signal to be sent to the process.
*/
virtual void send_signal_or_throw(Signal signal);
/**
* @brief Sends a signal to this signalable object.
* @param [in] signal The signal to be sent to the process.
* @param [out] e Set to contain an error if an issue arises.
*/
virtual void send_signal(Signal signal, std::error_code& e) noexcept(true);
protected:
CORE_POSIX_DLL_LOCAL explicit Signalable(pid_t pid);
private:
struct CORE_POSIX_DLL_LOCAL Private;
std::shared_ptr<Private> d;
};
}
}
#endif // CORE_POSIX_SIGNALABLE_H_

View file

@ -0,0 +1,46 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef CORE_POSIX_STANDARD_STREAM_H_
#define CORE_POSIX_STANDARD_STREAM_H_
#include <core/posix/visibility.h>
#include <cstdint>
namespace core
{
namespace posix
{
/**
* @brief The StandardStream enum wraps the POSIX standard streams.
*/
enum class StandardStream : std::uint8_t
{
empty = 0,
stdin = 1 << 0,
stdout = 1 << 1,
stderr = 1 << 2
};
CORE_POSIX_DLL_PUBLIC StandardStream operator|(StandardStream l, StandardStream r);
CORE_POSIX_DLL_PUBLIC StandardStream operator&(StandardStream l, StandardStream r);
}
}
#endif // CORE_POSIX_STANDARD_STREAM_H_

View file

@ -0,0 +1,128 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef CORE_POSIX_THIS_PROCESS_H_
#define CORE_POSIX_THIS_PROCESS_H_
#include <core/posix/visibility.h>
#include <functional>
#include <iosfwd>
#include <string>
#include <system_error>
namespace core
{
namespace posix
{
class Process;
namespace this_process
{
namespace env
{
/**
* @brief for_each invokes a functor for every key-value pair in the environment.
* @param [in] functor Invoked for every key-value pair.
*/
CORE_POSIX_DLL_PUBLIC void for_each(
const std::function<void(const std::string&, const std::string&)>& functor) noexcept(true);
/**
* @brief get queries the value of an environment variable.
* @throw std::runtime_error if there is no variable with the given key defined in the env.
* @param [in] key Name of the variable to query the value for.
* @return Contents of the variable.
*/
CORE_POSIX_DLL_PUBLIC std::string get_or_throw(const std::string& key);
/**
* @brief get queries the value of an environment variable.
* @param [in] key Name of the variable to query the value for.
* @param [in] default_value Default value to return when key is not present in the environment.
* @return Contents of the variable or an empty string if the variable is not defined.
*/
CORE_POSIX_DLL_PUBLIC std::string get(
const std::string& key,
const std::string& default_value = std::string()) noexcept(true);
/**
* @brief unset_or_throw removes the variable with name key from the environment.
* @throw std::system_error in case of errors.
* @param [in] key Name of the variable to unset.
*/
CORE_POSIX_DLL_PUBLIC void unset_or_throw(const std::string& key);
/**
* @brief unset removes the variable with name key from the environment.
* @return false in case of errors, true otherwise.
* @param [in] key Name of the variable to unset.
* @param [out] se Receives error details if unset returns false.
*/
CORE_POSIX_DLL_PUBLIC bool unset(const std::string& key,
std::error_code& se) noexcept(true);
/**
* @brief set_or_throw will adjust the contents of the variable identified by key to the provided value.
* @throw std::system_error in case of errors.
* @param [in] key Name of the variable to set the value for.
* @param [in] value New contents of the variable.
*/
CORE_POSIX_DLL_PUBLIC void set_or_throw(const std::string& key,
const std::string& value);
/**
* @brief set will adjust the contents of the variable identified by key to the provided value.
* @return false in case of errors, true otherwise.
* @param [in] key Name of the variable to set the value for.
* @param [in] value New contents of the variable.
* @param [out] se Receives the details in case of errors.
*/
CORE_POSIX_DLL_PUBLIC bool set(const std::string &key,
const std::string &value,
std::error_code& se) noexcept(true);
}
/**
* @brief Returns a Process instance corresponding to this process.
*/
CORE_POSIX_DLL_PUBLIC Process instance() noexcept(true);
/**
* @brief Query the parent of the process.
* @return The parent of the process.
*/
CORE_POSIX_DLL_PUBLIC Process parent() noexcept(true);
/**
* @brief Access this process's stdin.
*/
CORE_POSIX_DLL_PUBLIC std::istream& cin() noexcept(true);
/**
* @brief Access this process's stdout.
*/
CORE_POSIX_DLL_PUBLIC std::ostream& cout() noexcept(true);
/**
* @brief Access this process's stderr.
*/
CORE_POSIX_DLL_PUBLIC std::ostream& cerr() noexcept(true);
}
}
}
#endif // CORE_POSIX_THIS_PROCESS_H_

View file

@ -0,0 +1,30 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef CORE_POSIX_VISIBILITY_H_
#define CORE_POSIX_VISIBILITY_H_
#if __GNUC__ >= 4
#define CORE_POSIX_DLL_PUBLIC __attribute__ ((visibility ("default")))
#define CORE_POSIX_DLL_LOCAL __attribute__ ((visibility ("hidden")))
#else
#define CORE_POSIX_DLL_PUBLIC
#define CORE_POSIX_DLL_LOCAL
#endif
#endif // CORE_POSIX_VISIBILITY_H_

View file

@ -0,0 +1,104 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef CORE_POSIX_WAIT_H_
#define CORE_POSIX_WAIT_H_
#include <core/posix/exit.h>
#include <core/posix/signal.h>
#include <core/posix/visibility.h>
#include <bitset>
#include <cstdint>
#include <sys/wait.h>
namespace core
{
namespace posix
{
namespace wait
{
/**
* @brief Flags enumerates different behavior when waiting for a child process to change state.
*/
enum class Flags : std::uint8_t
{
continued = WCONTINUED, ///< Also wait for a child to continue after having been stopped.
untraced = WUNTRACED, ///< Also wait for state changes in untraced children.
no_hang = WNOHANG ///< Do not block if a child process hasn't changed state.
};
CORE_POSIX_DLL_PUBLIC Flags operator|(Flags l, Flags r);
/**
* @brief The Result struct encapsulates the result of waiting for a process state change.
*/
struct CORE_POSIX_DLL_PUBLIC Result
{
/**
* @brief The status of the process/wait operation.
*/
enum class Status
{
undefined, ///< Marks an undefined state.
no_state_change, ///< No state change occured.
exited, ///< The process exited normally.
signaled, ///< The process was signalled and terminated.
stopped, ///< The process was signalled and stopped.
continued ///< The process resumed operation.
} status = Status::undefined;
/**
* @brief Union of result-specific details.
*/
union
{
/**
* Contains the exit status of the process if status == Status::exited.
*/
struct
{
exit::Status status; ///< Exit status of the process.
} if_exited;
/**
* Contains the signal that caused the process to terminate if status == Status::signaled.
*/
struct
{
Signal signal; ///< Signal that caused the process to terminate.
bool core_dumped; ///< true if the process termination resulted in a core dump.
} if_signaled;
/**
* Contains the signal that caused the process to terminate if status == Status::stopped.
*/
struct
{
Signal signal; ///< Signal that caused the process to terminate.
} if_stopped;
} detail;
};
}
}
}
#endif // CORE_POSIX_WAIT_H_

View file

@ -0,0 +1,297 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef COM_UBUNTU_SIGNAL_H_
#define COM_UBUNTU_SIGNAL_H_
#include <core/connection.h>
#include <functional>
#include <iostream>
#include <list>
#include <mutex>
#include <set>
namespace core
{
/**
* @brief A signal class that observers can subscribe to.
* @tparam Arguments List of argument types passed on to observers when the signal is emitted.
*/
template<typename ...Arguments>
class Signal
{
public:
/**
* @brief Slot is the function type that observers have to provide to connect to this signal.
*/
typedef std::function<void(Arguments...)> Slot;
private:
struct SlotWrapper
{
void operator()(Arguments... args)
{
dispatcher(std::bind(slot, args...));
}
Slot slot;
Connection::Dispatcher dispatcher;
Connection connection;
};
public:
/**
* @brief Signal constructs a new instance. Never throws.
*/
inline Signal() noexcept(true) : d(new Private())
{
}
inline ~Signal()
{
std::lock_guard<std::mutex> lg(d->guard);
for (auto slot : d->slot_list)
slot.connection.reset();
}
// Copy construction, assignment and equality comparison are disabled.
Signal(const Signal&) = delete;
Signal& operator=(const Signal&) = delete;
bool operator==(const Signal&) const = delete;
/**
* @brief Connects the provided slot to this signal instance.
*
* Calling this method is thread-safe and synchronized with any
* other connect, signal emission or disconnect calls.
*
* @param slot The function to be called when the signal is emitted.
* @return A connection object corresponding to the signal-slot connection.
*/
inline Connection connect(const Slot& slot) const
{
// Helpers to initialize an invalid connection.
static const Connection::Disconnector empty_disconnector{};
static const Connection::DispatcherInstaller empty_dispatcher_installer{};
// The default dispatcher immediately executes the function object
// provided as argument on whatever thread is currently running.
static const Connection::Dispatcher default_dispatcher
= [](const std::function<void()>& handler) { handler(); };
Connection conn{empty_disconnector, empty_dispatcher_installer};
std::lock_guard<std::mutex> lg(d->guard);
auto result = d->slot_list.insert(
d->slot_list.end(),
SlotWrapper{slot, default_dispatcher, conn});
// We implicitly share our internal state with the connection here
// by passing in our private bits contained in 'd' to the std::bind call.
// This admittedly uncommon approach allows us to cleanly manage connection
// and signal lifetimes without the need to mark everything as mutable.
conn.d->disconnector = std::bind(
&Private::disconnect_slot_for_iterator,
d,
result);
conn.d->dispatcher_installer = std::bind(
&Private::install_dispatcher_for_iterator,
d,
std::placeholders::_1,
result);
return conn;
}
/**
* @brief operator () emits the signal with the provided parameters.
*
* Please note that signal emissions might not be delivered immediately to
* registered slots, depending on whether the respective connection is dispatched
* via a queueing dispatcher. For that reason, the lifetime of the arguments has to
* exceed the scope of the call to this operator and its surrounding scope.
*
* @param args The arguments to be passed on to registered slots.
*/
inline void operator()(Arguments... args)
{
std::lock_guard<std::mutex> lg(d->guard);
for(auto slot : d->slot_list)
{
slot(args...);
}
}
private:
struct Private
{
typedef std::list<SlotWrapper> SlotList;
inline void disconnect_slot_for_iterator(typename SlotList::iterator it)
{
std::lock_guard<std::mutex> lg(guard);
slot_list.erase(it);
}
inline void install_dispatcher_for_iterator(const Connection::Dispatcher& dispatcher,
typename SlotList::iterator it)
{
std::lock_guard<std::mutex> lg(guard);
it->dispatcher = dispatcher;
}
std::mutex guard;
SlotList slot_list;
};
std::shared_ptr<Private> d;
};
/**
* @brief A signal class that observers can subscribe to,
* template specialization for signals without arguments.
*/
template<>
class Signal<void>
{
public:
/**
* @brief Slot is the function type that observers have to provide to connect to this signal.
*/
typedef std::function<void()> Slot;
private:
struct SlotWrapper
{
void operator()()
{
dispatcher(slot);
}
Slot slot;
Connection::Dispatcher dispatcher;
Connection connection;
};
public:
/**
* @brief Signal constructs a new instance. Never throws.
*/
inline Signal() noexcept(true) : d(new Private())
{
}
inline ~Signal()
{
std::lock_guard<std::mutex> lg(d->guard);
for (auto slot : d->slot_list)
slot.connection.reset();
}
// Copy construction, assignment and equality comparison are disabled.
Signal(const Signal&) = delete;
Signal& operator=(const Signal&) = delete;
bool operator==(const Signal&) const = delete;
/**
* @brief Connects the provided slot to this signal instance.
*
* Calling this method is thread-safe and synchronized with any
* other connect, signal emission or disconnect calls.
*
* @param slot The function to be called when the signal is emitted.
* @return A connection object corresponding to the signal-slot connection.
*/
inline Connection connect(const Slot& slot) const
{
// Helpers to initialize an invalid connection.
static const Connection::Disconnector empty_disconnector{};
static const Connection::DispatcherInstaller empty_dispatcher_installer{};
// The default dispatcher immediately executes the function object
// provided as argument on whatever thread is currently running.
static const Connection::Dispatcher default_dispatcher
= [](const std::function<void()>& handler) { handler(); };
Connection conn{empty_disconnector, empty_dispatcher_installer};
std::lock_guard<std::mutex> lg(d->guard);
auto result = d->slot_list.insert(
d->slot_list.end(),
SlotWrapper{slot, default_dispatcher, conn});
// We implicitly share our internal state with the connection here
// by passing in our private bits contained in 'd' to the std::bind call.
// This admittedly uncommon approach allows us to cleanly manage connection
// and signal lifetimes without the need to mark everything as mutable.
conn.d->disconnector = std::bind(
&Private::disconnect_slot_for_iterator,
d,
result);
conn.d->dispatcher_installer = std::bind(
&Private::install_dispatcher_for_iterator,
d,
std::placeholders::_1,
result);
return conn;
}
/**
* @brief operator () emits the signal.
*
* Please note that signal emissions might not be delivered immediately to
* registered slots, depending on whether the respective connection is dispatched
* via a queueing dispatcher.
*/
inline void operator()()
{
std::lock_guard<std::mutex> lg(d->guard);
for(auto slot : d->slot_list)
{
slot();
}
}
private:
struct Private
{
typedef std::list<SlotWrapper> SlotList;
inline void disconnect_slot_for_iterator(typename SlotList::iterator it)
{
std::lock_guard<std::mutex> lg(guard);
slot_list.erase(it);
}
inline void install_dispatcher_for_iterator(const Connection::Dispatcher& dispatcher,
typename SlotList::iterator it)
{
std::lock_guard<std::mutex> lg(guard);
it->dispatcher = dispatcher;
}
std::mutex guard;
SlotList slot_list;
};
std::shared_ptr<Private> d;
};
}
#endif // COM_UBUNTU_SIGNAL_H_

View file

@ -0,0 +1,99 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voss <thomas.voss@canonical.com>
*/
#ifndef CORE_TESTING_CROSS_PROCESS_SYNC_H_
#define CORE_TESTING_CROSS_PROCESS_SYNC_H_
#include <core/posix/visibility.h>
#include <cstdint>
#include <chrono>
#include <stdexcept>
namespace core
{
namespace testing
{
/**
* @brief A cross-process synchronization primitive that supports simple wait-condition-like scenarios.
*/
class CORE_POSIX_DLL_PUBLIC CrossProcessSync
{
public:
struct Error
{
Error() = delete;
~Error() = delete;
/**
* @brief Thrown if any of the *_for functions times out.
*/
struct Timeout : public std::runtime_error
{
Timeout() : std::runtime_error("Timeout while waiting for event to happen.")
{
}
};
};
/**
* @brief Constructs a new sync element.
*/
CrossProcessSync();
/**
* @brief Copy c'tor, duping the underlying fds.
* @param rhs The instance to copy.
*/
CrossProcessSync(const CrossProcessSync& rhs);
/**
* @brief Closes the underlying fds.
*/
~CrossProcessSync() noexcept;
/**
* @brief operator =, dup's the underlying fds.
* @param rhs The instance to assign from.
* @return A mutable reference to this instance.
*/
CrossProcessSync& operator=(const CrossProcessSync& rhs);
/**
* @brief Try to signal the other side that we are ready for at most duration milliseconds.
* @throw Error::Timeout in case of a timeout.
* @throw std::system_error for problems with the underlying pipe.
*/
void try_signal_ready_for(const std::chrono::milliseconds& duration);
/**
* @brief Wait for the other sides to signal readiness for at most duration milliseconds.
* @return The number of ready signals that have been collected since creation.
* @throw Error::Timeout in case of a timeout.
* @throw std::system_error for problems with the underlying pipe.
*/
std::uint32_t wait_for_signal_ready_for(const std::chrono::milliseconds& duration);
private:
int fds[2]; ///< The cross-process pipe.
std::uint32_t counter; ///< Counts the number of times the sync has been signalled.
};
}
}
#endif // CORE_TESTING_CROSS_PROCESS_SYNC_H_

View file

@ -0,0 +1,115 @@
/*
* Copyright © 2012-2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef CORE_TESTING_FORK_AND_RUN_H_
#define CORE_TESTING_FORK_AND_RUN_H_
#include <core/posix/exit.h>
#include <core/posix/fork.h>
#include <core/posix/visibility.h>
#include <functional>
namespace core
{
namespace testing
{
/**
* @brief The ForkAndRunResult enum models the different failure modes of fork_and_run.
*/
enum class ForkAndRunResult
{
empty = 0, ///< Special value indicating no bit being set.
client_failed = 1 << 0, ///< The client failed.
service_failed = 1 << 1 ///< The service failed.
};
CORE_POSIX_DLL_PUBLIC ForkAndRunResult operator|(ForkAndRunResult lhs, ForkAndRunResult rhs);
CORE_POSIX_DLL_PUBLIC ForkAndRunResult operator&(ForkAndRunResult lhs, ForkAndRunResult rhs);
/**
* @brief Forks two processes for both the service and the client.
*
* The function does the following:
* - Forks a process for the service and runs the respective closure.
* - Forks a process for the client and runs the respective closure.
* - After the client has finished, the service is signalled with sigterm.
*
* @throw std::system_error if an error occured during process interaction.
* @throw std::runtime_error for signalling all other error conditions.
* @param [in] service The service to be executed in a child process.
* @param [in] client The client to be executed in a child process.
* @return ForkAndRunResult indicating if either of service or client failed.
*/
CORE_POSIX_DLL_PUBLIC ForkAndRunResult fork_and_run(
const std::function<core::posix::exit::Status()>& service,
const std::function<core::posix::exit::Status()>& client);
}
}
/**
* Test definition macro which runs a TEST in a forked process.
* Note that you can only use EXPECT_*, not
* ASSERT_*!
*
* Usage:
* TESTP(test_suite, test_name, {
* test code ...
* EXPECT_* ...
* })
*/
#define TESTP(test_suite, test_name, CODE) \
TEST(test_suite, test_name) { \
auto test = [&]() { \
CODE \
return HasFailure() ? core::posix::exit::Status::failure \
: core::posix::exit::Status::success; \
}; \
auto child = core::posix::fork( \
test, \
core::posix::StandardStream::empty); \
auto result = child.wait_for(core::posix::wait::Flags::untraced); \
EXPECT_EQ(core::posix::wait::Result::Status::exited, result.status); \
EXPECT_EQ(core::posix::exit::Status::success, result.detail.if_exited.status); \
} \
/**
* Test definition macro which runs a TEST_F in a forked process.
* Note that you can only use EXPECT_*, not ASSERT_*!
*
* Usage:
* TESTP_F(FixtureName, TestName, {
* ... test code ...
* EXPECT_* ...
* })
*/
#define TESTP_F(test_fixture, test_name, CODE) \
TEST_F(test_fixture, test_name) { \
auto test = [&]() { \
CODE \
return HasFailure() ? core::posix::exit::Status::failure \
: core::posix::exit::Status::success; \
}; \
auto child = core::posix::fork( \
test, \
core::posix::StandardStream::empty); \
auto result = child.wait_for(core::posix::wait::Flags::untraced); \
EXPECT_EQ(core::posix::wait::Result::Status::exited, result.status); \
EXPECT_EQ(core::posix::exit::Status::success, result.detail.if_exited.status); \
} \
#endif // CORE_TESTING_FORK_AND_RUN_H_

View file

@ -0,0 +1,47 @@
# Copyright © 2013 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Authored by: Thomas Voss <thomas.voss@canonical.com>
add_library(
process-cpp
core/posix/backtrace.h
core/posix/backtrace.cpp
core/posix/child_process.cpp
core/posix/exec.cpp
core/posix/fork.cpp
core/posix/process.cpp
core/posix/process_group.cpp
core/posix/signal.cpp
core/posix/signalable.cpp
core/posix/standard_stream.cpp
core/posix/wait.cpp
core/posix/this_process.cpp
core/posix/linux/proc/process/oom_adj.cpp
core/posix/linux/proc/process/oom_score.cpp
core/posix/linux/proc/process/oom_score_adj.cpp
core/posix/linux/proc/process/stat.cpp
core/testing/cross_process_sync.cpp
core/testing/fork_and_run.cpp
)
target_link_libraries(
process-cpp
${Boost_LIBRARIES}
${CMAKE_THREAD_LIBS_INIT}
)

View file

@ -0,0 +1,24 @@
# Copyright © 2013 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Authored by: Thomas Voss <thomas.voss@canonical.com>
add_library(
posix-process
process.cpp
)
add_subdirectory(linux)

View file

@ -0,0 +1,153 @@
/*
* Copyright © 2014 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#include "backtrace.h"
#include <cxxabi.h>
#include <execinfo.h>
namespace bt = core::posix::backtrace;
namespace impl
{
std::tuple<std::string, bool> demangle(const std::string& symbol)
{
int status = 1;
auto result = abi::__cxa_demangle(symbol.c_str(),
nullptr,
nullptr,
&status);
if (!result || status != 0)
{
return std::make_tuple(std::string(), false);
}
std::string s{result};
::free(result);
return std::make_tuple(s, true);
}
struct Frame : public bt::Frame
{
struct Symbol : public bt::Frame::Symbol
{
Symbol(const char* symbol) : raw_(symbol)
{
auto first = raw_.find_first_of("(");
auto last = raw_.find_last_of(")");
if (first != std::string::npos && last != std::string::npos)
{
auto mangled_symbol = raw_.substr(first+1,
(last-1) - (first+1));
auto plus = mangled_symbol.find_first_of("+");
if (plus != std::string::npos)
mangled_symbol.erase(plus);
std::tie(demangled_, is_cxx_) = demangle(mangled_symbol);
if (!is_cxx_)
demangled_ = raw_;
}
}
bool is_cxx() const
{
return is_cxx_;
}
std::string demangled() const
{
return demangled_;
}
std::string raw() const
{
return raw_;
}
std::string raw_;
std::string demangled_;
bool is_cxx_ = false;
};
std::size_t depth_;
void* frame_pointer_;
Symbol symbol_;
Frame(std::size_t depth, void* frame_pointer, const char* symbol)
: depth_(depth),
frame_pointer_(frame_pointer),
symbol_(symbol)
{
}
std::size_t depth() const
{
return depth_;
}
virtual void* frame_pointer() const
{
return frame_pointer_;
}
const Symbol& symbol() const
{
return symbol_;
}
};
}
std::shared_ptr<bt::Frame::Symbol> bt::Frame::Symbol::for_testing_from_raw_symbol(const char* symbol)
{
return std::shared_ptr<bt::Frame::Symbol>(new impl::Frame::Symbol(symbol));
}
void bt::visit_with_handler(const bt::FrameHandler& handler)
{
static const unsigned int max_frames=64;
void *frames[max_frames];
auto frame_count = ::backtrace(frames, max_frames);
auto symbols = ::backtrace_symbols(frames, frame_count);
struct Scope
{
Scope(char** symbols) : symbols(symbols)
{
}
~Scope()
{
::free(symbols);
}
char** symbols = nullptr;
} scope{symbols};
for (int i = 0; i < frame_count; i++)
{
impl::Frame frame(i, frames[i], symbols[i]);
if (!handler(frame))
return;
}
}

View file

@ -0,0 +1,122 @@
/*
* Copyright © 2014 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#ifndef CORE_POSIX_BACKTRACE_H_
#define CORE_POSIX_BACKTRACE_H_
#include <core/posix/visibility.h>
#include <functional>
#include <memory>
#include <string>
namespace core
{
namespace posix
{
namespace backtrace
{
/**
* @brief The Frame class models an individual frame of a backtrace.
*/
class Frame
{
public:
/**
* @brief The Symbol class models the symbolic representation of a frame pointer.
*/
class Symbol
{
public:
static std::shared_ptr<Symbol> for_testing_from_raw_symbol(const char* symbol);
Symbol(const Symbol&) = delete;
virtual ~Symbol() = default;
Symbol& operator=(const Symbol&) = delete;
/**
* @brief is_cxx checks whether the symbol refers to a mangled C++ symbol.
* @return true iff the symbol refers to a mangled C++ symbol.
*/
virtual bool is_cxx() const = 0;
/**
* @brief demangled returns the demangled C++ symbol name or raw.
*/
virtual std::string demangled() const = 0;
/**
* @brief raw The raw symbolic representation of a frame pointer.
* @return
*/
virtual std::string raw() const = 0;
protected:
Symbol() = default;
};
Frame(const Frame&) = delete;
virtual ~Frame() = default;
Frame& operator=(const Frame&) = delete;
/**
* @brief depth returns the depth of this frame in the overall backtrace.
*/
virtual std::size_t depth() const = 0;
/**
* @brief frame_pointer returns the the raw frame pointer of this frame.
* @return
*/
virtual void* frame_pointer() const = 0;
/**
* @brief symbol returns the symbolic representation of this frame.
*/
virtual const Symbol& symbol() const = 0;
protected:
Frame() = default;
};
/**
* @brief FrameHandler is the functor invoked for every frame of a backtrace.
*
* A FrameHandler should return true if it wants to continue walking the stack
* or false otherwise.
*/
typedef std::function<bool(const Frame& frame)> FrameHandler;
/**
*@brief visit_with_handler iterates the backtrace of the calling program,
*invoking the handler for every frame.
*
* A FrameHandler should return true if it wants to continue walking the stack
* or false otherwise
*
* @param handler The handler invoked for every frame.
*/
void CORE_POSIX_DLL_PUBLIC visit_with_handler(const FrameHandler& handler);
}
}
}
#endif // CORE_POSIX_BACKTRACE_H_

View file

@ -0,0 +1,397 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#include <core/posix/child_process.h>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <atomic>
#include <fstream>
#include <mutex>
#include <unordered_map>
#include <fcntl.h>
#include <poll.h>
#include <unistd.h>
#include <sys/eventfd.h>
#include <sys/signalfd.h>
namespace io = boost::iostreams;
namespace
{
struct DeathObserverImpl : public core::posix::ChildProcess::DeathObserver
{
DeathObserverImpl(const std::shared_ptr<core::posix::SignalTrap>& trap)
: on_sig_child_connection
{
trap->signal_raised().connect([this](core::posix::Signal signal)
{
switch (signal)
{
case core::posix::Signal::sig_chld:
on_sig_child();
break;
default:
break;
}
})
}
{
if (!trap->has(core::posix::Signal::sig_chld))
throw std::logic_error(
"DeathObserver::DeathObserverImpl: Given SignalTrap"
" instance does not trap Signal::sig_chld.");
}
bool add(const core::posix::ChildProcess& process) override
{
if (process.pid() == -1)
return false;
std::lock_guard<std::mutex> lg(guard);
bool added = false;
auto new_process = std::make_pair(process.pid(), process);
std::tie(std::ignore, added) = children.insert(new_process);
if (added)
{
// The process may have died between it's instantiation and it
// being added to the children map. Check that it's still alive.
int status{-1};
if (::waitpid(process.pid(), &status, WNOHANG) != 0) // child no longer alive
{
// we missed the SIGCHLD signal so we must now manually
// inform our subscribers.
signals.child_died(new_process.second);
children.erase(new_process.first);
return false;
}
}
return added;
}
bool has(const core::posix::ChildProcess& process) const override
{
std::lock_guard<std::mutex> lg(guard);
return children.count(process.pid()) > 0;
}
const core::Signal<core::posix::ChildProcess>& child_died() const override
{
return signals.child_died;
}
void on_sig_child() override
{
pid_t pid{-1}; int status{-1};
while (true)
{
pid = ::waitpid(0, &status, WNOHANG);
if (pid == -1)
{
if (errno == ECHILD)
{
break; // No more children
}
continue; // Ignore stray SIGCHLD signals
}
else if (pid == 0)
{
break; // No more children
}
else
{
std::lock_guard<std::mutex> lg(guard);
auto it = children.find(pid);
if (it != children.end())
{
if (WIFSIGNALED(status) || WIFEXITED(status))
{
signals.child_died(it->second);
children.erase(it);
}
}
}
}
}
mutable std::mutex guard;
std::unordered_map<pid_t, core::posix::ChildProcess> children;
core::ScopedConnection on_sig_child_connection;
struct
{
core::Signal<core::posix::ChildProcess> child_died;
} signals;
};
}
std::unique_ptr<core::posix::ChildProcess::DeathObserver>
core::posix::ChildProcess::DeathObserver::create_once_with_signal_trap(
std::shared_ptr<core::posix::SignalTrap> trap)
{
static std::atomic<bool> has_been_created_once{false};
if (has_been_created_once.exchange(true))
throw std::runtime_error
{
"DeathObserver::create_once_with_signal_trap: "
"Cannot create more than one instance."
};
try
{
std::unique_ptr<core::posix::ChildProcess::DeathObserver> result
{
new DeathObserverImpl{trap}
};
return result;
} catch(...)
{
// We make sure that a throwing c'tor does not impact our ability to
// retry creation of a DeathObserver instance.
has_been_created_once.store(false);
std::rethrow_exception(std::current_exception());
}
assert(false && "We should never reach here.");
// Silence the compiler.
return std::unique_ptr<core::posix::ChildProcess::DeathObserver>{};
}
namespace core
{
namespace posix
{
ChildProcess::Pipe ChildProcess::Pipe::invalid()
{
static Pipe p;
static std::once_flag flag;
std::call_once(flag, [&]() { p.close_read_fd(); p.close_write_fd(); });
return p;
}
ChildProcess::Pipe::Pipe()
{
int rc = ::pipe(fds);
if (rc == -1)
throw std::system_error(errno, std::system_category());
}
ChildProcess::Pipe::Pipe(const ChildProcess::Pipe& rhs) : fds{-1, -1}
{
if (rhs.fds[0] != -1)
fds[0] = ::dup(rhs.fds[0]);
if (rhs.fds[1] != -1)
fds[1] = ::dup(rhs.fds[1]);
}
ChildProcess::Pipe::~Pipe()
{
if (fds[0] != -1)
::close(fds[0]);
if (fds[1] != -1)
::close(fds[1]);
}
int ChildProcess::Pipe::read_fd() const
{
return fds[0];
}
void ChildProcess::Pipe::close_read_fd()
{
if (fds[0] != -1)
{
::close(fds[0]);
fds[0] = -1;
}
}
int ChildProcess::Pipe::write_fd() const
{
return fds[1];
}
void ChildProcess::Pipe::close_write_fd()
{
if (fds[1] != -1)
{
::close(fds[1]);
fds[1] = -1;
}
}
ChildProcess::Pipe& ChildProcess::Pipe::operator=(const ChildProcess::Pipe& rhs)
{
if (fds[0] != -1)
::close(fds[0]);
if (fds[1] != -1)
::close(fds[1]);
if (rhs.fds[0] != -1)
fds[0] = ::dup(rhs.fds[0]);
else
fds[0] = -1;
if (rhs.fds[1] != -1)
fds[1] = ::dup(rhs.fds[1]);
else
fds[1] = -1;
return *this;
}
struct ChildProcess::Private
{
// stdin and stdout are always "relative" to the childprocess, i.e., we
// write to stdin of the child process and read from its stdout.
Private(pid_t pid,
const ChildProcess::Pipe& stderr,
const ChildProcess::Pipe& stdin,
const ChildProcess::Pipe& stdout)
: pipes{stderr, stdin, stdout},
serr(pipes.stderr.read_fd(), io::never_close_handle),
sin(pipes.stdin.write_fd(), io::never_close_handle),
sout(pipes.stdout.read_fd(), io::never_close_handle),
cerr(&serr),
cin(&sin),
cout(&sout),
original_parent_pid(::getpid()),
original_child_pid(pid)
{
}
~Private()
{
// Check if we are in the original parent process.
if (original_parent_pid == getpid())
{
// If so, check if we are considering a valid pid here.
// If so, we kill the original child.
if (original_child_pid != -1)
::kill(original_child_pid, SIGKILL);
}
}
struct
{
ChildProcess::Pipe stdin;
ChildProcess::Pipe stdout;
ChildProcess::Pipe stderr;
} pipes;
io::stream_buffer<io::file_descriptor_source> serr;
io::stream_buffer<io::file_descriptor_sink> sin;
io::stream_buffer<io::file_descriptor_source> sout;
std::istream cerr;
std::ostream cin;
std::istream cout;
// We need to store the original parent pid as we might have been forked
// and with our automatic cleanup in place, it might happen that the d'tor
// is called from the child process.
pid_t original_parent_pid;
pid_t original_child_pid;
};
ChildProcess ChildProcess::invalid()
{
// We take the init process as child.
static const pid_t invalid_pid = 1;
return ChildProcess(invalid_pid, Pipe::invalid(), Pipe::invalid(), Pipe::invalid());
}
ChildProcess::ChildProcess(pid_t pid,
const ChildProcess::Pipe& stdin_pipe,
const ChildProcess::Pipe& stdout_pipe,
const ChildProcess::Pipe& stderr_pipe)
: Process(pid),
d(new Private{pid, stdin_pipe, stdout_pipe, stderr_pipe})
{
}
ChildProcess::~ChildProcess()
{
}
wait::Result ChildProcess::wait_for(const wait::Flags& flags)
{
int status = -1;
pid_t result_pid = ::waitpid(pid(), std::addressof(status), static_cast<int>(flags));
if (result_pid == -1)
throw std::system_error(errno, std::system_category());
wait::Result result;
if (result_pid == 0)
{
result.status = wait::Result::Status::no_state_change;
return result;
}
if (WIFEXITED(status))
{
result.status = wait::Result::Status::exited;
result.detail.if_exited.status = static_cast<exit::Status>(WEXITSTATUS(status));
} else if (WIFSIGNALED(status))
{
result.status = wait::Result::Status::signaled;
result.detail.if_signaled.signal = static_cast<Signal>(WTERMSIG(status));
result.detail.if_signaled.core_dumped = WCOREDUMP(status);
} else if (WIFSTOPPED(status))
{
result.status = wait::Result::Status::stopped;
result.detail.if_stopped.signal = static_cast<Signal>(WSTOPSIG(status));
} else if (WIFCONTINUED(status))
{
result.status = wait::Result::Status::continued;
}
return result;
}
std::istream& ChildProcess::cerr()
{
return d->cerr;
}
std::ostream& ChildProcess::cin()
{
return d->cin;
}
std::istream& ChildProcess::cout()
{
return d->cout;
}
}
}

View file

@ -0,0 +1,75 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#include <core/posix/exec.h>
#include <core/posix/fork.h>
#include <core/posix/standard_stream.h>
#include <iostream>
#include <cstring>
#include <unistd.h>
namespace core
{
namespace posix
{
ChildProcess exec(const std::string& fn,
const std::vector<std::string>& argv,
const std::map<std::string, std::string>& env,
const StandardStream& flags)
{
std::function<void()> null_function = [](){};
return exec(fn, argv, env, flags, null_function);
}
ChildProcess exec(const std::string& fn,
const std::vector<std::string>& argv,
const std::map<std::string, std::string>& env,
const StandardStream& flags,
const std::function<void()>& child_setup)
{
return posix::fork([fn, argv, env, child_setup]()
{
char** it; char** pargv; char** penv;
it = pargv = new char*[argv.size()+2];
*it = ::strdup(fn.c_str());
it++;
for (auto element : argv)
{
*it = ::strdup(element.c_str());
it++;
}
*it = nullptr;
it = penv = new char*[env.size()+1];
for (auto pair : env)
{
*it = ::strdup((pair.first + "=" + pair.second).c_str());
it++;
}
*it = nullptr;
child_setup();
return static_cast<posix::exit::Status>(execve(fn.c_str(), pargv, penv));
}, flags);
}
}
}

View file

@ -0,0 +1,180 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#include <core/posix/exit.h>
#include <core/posix/fork.h>
#include "backtrace.h"
#include <iomanip>
#include <iostream>
#include <system_error>
#include <unistd.h>
namespace
{
void redirect_stream_to_fd(int fd, int stream)
{
auto rc = ::dup2(fd, stream);
if (rc == -1)
throw std::system_error(errno, std::system_category());
}
void print_backtrace(std::ostream& out, const std::string& line_prefix)
{
core::posix::backtrace::visit_with_handler([&out, line_prefix](const core::posix::backtrace::Frame& frame)
{
out << line_prefix << std::dec << std::setw(2) << frame.depth() << "@" << std::hex << std::setw(14) << frame.frame_pointer() << ": "
<< (frame.symbol().is_cxx() ? frame.symbol().demangled() : frame.symbol().raw()) << std::endl;
return true;
});
}
}
namespace core
{
namespace posix
{
bool is_child(pid_t pid) { return pid == 0; }
ChildProcess fork(const std::function<posix::exit::Status()>& main,
const StandardStream& flags)
{
ChildProcess::Pipe stdin_pipe{ChildProcess::Pipe::invalid()};
ChildProcess::Pipe stdout_pipe{ChildProcess::Pipe::invalid()};
ChildProcess::Pipe stderr_pipe{ChildProcess::Pipe::invalid()};
if ((flags & StandardStream::stdin) != StandardStream::empty)
stdin_pipe = ChildProcess::Pipe();
if ((flags & StandardStream::stdout) != StandardStream::empty)
stdout_pipe = ChildProcess::Pipe();
if ((flags & StandardStream::stderr) != StandardStream::empty)
stderr_pipe = ChildProcess::Pipe();
pid_t pid = ::fork();
if (pid == -1)
throw std::system_error(errno, std::system_category());
if (is_child(pid))
{
posix::exit::Status result = posix::exit::Status::failure;
try
{
stdin_pipe.close_write_fd();
stdout_pipe.close_read_fd();
stderr_pipe.close_read_fd();
// We replace stdin and stdout of the child process first:
if ((flags & StandardStream::stdin) != StandardStream::empty)
redirect_stream_to_fd(stdin_pipe.read_fd(), STDIN_FILENO);
if ((flags & StandardStream::stdout) != StandardStream::empty)
redirect_stream_to_fd(stdout_pipe.write_fd(), STDOUT_FILENO);
if ((flags & StandardStream::stderr) != StandardStream::empty)
redirect_stream_to_fd(stderr_pipe.write_fd(), STDERR_FILENO);
result = main();
} catch(const std::exception& e)
{
std::cerr << "core::posix::fork(): An unhandled std::exception occured in the child process:" << std::endl
<< " what(): " << e.what() << std::endl;
print_backtrace(std::cerr, " ");
} catch(...)
{
std::cerr << "core::posix::fork(): An unhandled exception occured in the child process." << std::endl;
print_backtrace(std::cerr, " ");
}
// We have to ensure that we exit here. Otherwise, we run into
// all sorts of weird issues.
::exit(static_cast<int>(result));
}
// We are in the parent process, and create a process object
// corresponding to the newly forked process.
stdin_pipe.close_read_fd();
stdout_pipe.close_write_fd();
stderr_pipe.close_write_fd();
return ChildProcess(pid,
stdin_pipe,
stdout_pipe,
stderr_pipe);
}
ChildProcess vfork(const std::function<posix::exit::Status()>& main,
const StandardStream& flags)
{
ChildProcess::Pipe stdin_pipe, stdout_pipe, stderr_pipe;
pid_t pid = ::vfork();
if (pid == -1)
throw std::system_error(errno, std::system_category());
if (is_child(pid))
{
posix::exit::Status result = posix::exit::Status::failure;
try
{
// We replace stdin and stdout of the child process first:
stdin_pipe.close_write_fd();
stdout_pipe.close_read_fd();
stderr_pipe.close_read_fd();
// We replace stdin and stdout of the child process first:
if ((flags & StandardStream::stdin) != StandardStream::empty)
redirect_stream_to_fd(stdin_pipe.read_fd(), STDIN_FILENO);
if ((flags & StandardStream::stdout) != StandardStream::empty)
redirect_stream_to_fd(stdout_pipe.write_fd(), STDOUT_FILENO);
if ((flags & StandardStream::stderr) != StandardStream::empty)
redirect_stream_to_fd(stderr_pipe.write_fd(), STDERR_FILENO);
result = main();
} catch(const std::exception& e)
{
std::cerr << "core::posix::fork(): An unhandled std::exception occured in the child process:" << std::endl
<< " what(): " << e.what() << std::endl;
print_backtrace(std::cerr, " ");
} catch(...)
{
std::cerr << "core::posix::fork(): An unhandled exception occured in the child process." << std::endl;
print_backtrace(std::cerr, " ");
}
// We have to ensure that we exit here. Otherwise, we run into
// all sorts of weird issues.
::exit(static_cast<int>(result));
}
// We are in the parent process, and create a process object
// corresponding to the newly forked process.
// Close the parent's pipe end
stdin_pipe.close_read_fd();
stdout_pipe.close_write_fd();
stderr_pipe.close_write_fd();
return ChildProcess(pid,
stdin_pipe,
stdout_pipe,
stderr_pipe);
}
}
}

View file

@ -0,0 +1,28 @@
# Copyright © 2013 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Authored by: Thomas Voss <thomas.voss@canonical.com>
add_library(
linux-process
process.cpp
)
target_link_libraries(
linux-process
posix-process
)

View file

@ -0,0 +1,81 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#include <core/posix/linux/proc/process/oom_adj.h>
#include <core/posix/process.h>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <linux/oom.h>
namespace core
{
namespace posix
{
namespace linux
{
namespace proc
{
namespace process
{
int OomAdj::disable_value()
{
return OOM_DISABLE;
}
int OomAdj::min_value()
{
return OOM_ADJUST_MIN;
}
int OomAdj::max_value()
{
return OOM_ADJUST_MAX;
}
const posix::Process& operator>>(const posix::Process& process, OomAdj& adj)
{
std::stringstream ss; ss << "/proc/" << process.pid() << "/oom_adj";
std::ifstream in(ss.str());
in >> adj.value;
return process;
}
const posix::Process& operator<<(const posix::Process& process, const OomAdj& adj)
{
if (!adj.is_valid())
throw std::logic_error("Value for adjusting the oom score is invalid.");
std::stringstream ss; ss << "/proc/" << process.pid() << "/oom_adj";
std::ofstream out(ss.str());
out << adj.value;
return process;
}
}
}
}
}
}

View file

@ -0,0 +1,49 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#include <core/posix/linux/proc/process/oom_score.h>
#include <core/posix/process.h>
#include <fstream>
#include <sstream>
namespace core
{
namespace posix
{
namespace linux
{
namespace proc
{
namespace process
{
const posix::Process& operator>>(const posix::Process& process, OomScore& score)
{
std::stringstream ss; ss << "/proc/" << process.pid() << "/oom_score";
std::ifstream in(ss.str());
in >> score.value;
return process;
}
}
}
}
}
}

View file

@ -0,0 +1,76 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#include <core/posix/linux/proc/process/oom_score_adj.h>
#include <core/posix/process.h>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <linux/oom.h>
namespace core
{
namespace posix
{
namespace linux
{
namespace proc
{
namespace process
{
int OomScoreAdj::min_value()
{
return OOM_SCORE_ADJ_MIN;
}
int OomScoreAdj::max_value()
{
return OOM_SCORE_ADJ_MAX;
}
const posix::Process& operator>>(const posix::Process& process, OomScoreAdj& score_adj)
{
std::stringstream ss; ss << "/proc/" << process.pid() << "/oom_score_adj";
std::ifstream in(ss.str());
in >> score_adj.value;
return process;
}
const posix::Process& operator<<(const posix::Process& process, const OomScoreAdj& score_adj)
{
if (!score_adj.is_valid())
throw std::logic_error("Value for adjusting the oom score is invalid.");
std::stringstream ss; ss << "/proc/" << process.pid() << "/oom_score_adj";
std::ofstream out(ss.str());
out << score_adj.value;
return process;
}
}
}
}
}
}

View file

@ -0,0 +1,106 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#include <core/posix/linux/proc/process/stat.h>
#include <core/posix/process.h>
#include <fstream>
#include <istream>
#include <sstream>
namespace core
{
namespace posix
{
namespace linux
{
namespace proc
{
namespace process
{
std::istream& operator>>(std::istream& in, State& state)
{
char c; in >> c; state = static_cast<State>(c);
return in;
}
std::istream& operator>>(std::istream& in, Stat& stat)
{
in >> stat.pid
>> stat.executable
>> stat.state
>> stat.parent
>> stat.process_group
>> stat.session_id
>> stat.tty_nr
>> stat.controlling_process_group
>> stat.kernel_flags
>> stat.minor_faults_count
>> stat.minor_faults_count_by_children
>> stat.major_faults_count
>> stat.major_faults_count_by_children
>> stat.time.user
>> stat.time.system
>> stat.time.user_for_children
>> stat.time.system_for_children
>> stat.priority
>> stat.nice
>> stat.thread_count
>> stat.time_before_next_sig_alarm
>> stat.start_time
>> stat.size.virt
>> stat.size.resident_set
>> stat.size.resident_set_limit
>> stat.addresses.start_code
>> stat.addresses.end_code
>> stat.addresses.start_stack
>> stat.addresses.stack_pointer
>> stat.addresses.instruction_pointer
>> stat.signals.pending
>> stat.signals.blocked
>> stat.signals.ignored
>> stat.signals.caught
>> stat.channel
>> stat.swap_count
>> stat.swap_count_children
>> stat.exit_signal
>> stat.cpu_count
>> stat.realtime_priority
>> stat.scheduling_policy
>> stat.aggregated_block_io_delays
>> stat.guest_time
>> stat.guest_time_children;
return in;
}
const posix::Process& operator>>(const posix::Process& process, Stat& stat)
{
std::stringstream ss; ss << "/proc/" << process.pid() << "/stat";
std::ifstream in(ss.str());
in >> stat;
return process;
}
}
}
}
}
}

View file

@ -0,0 +1,40 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#include <core/posix/linux/proc/process/state.h>
#include <core/posix/process.h>
#include <istream>
namespace core
{
namespace posix
{
namespace linux
{
namespace proc
{
namespace process
{
}
}
}
}
}

View file

@ -0,0 +1,86 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#include <core/posix/process.h>
#include <core/posix/signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <iostream>
namespace core
{
namespace posix
{
struct Process::Private
{
pid_t pid;
};
Process Process::invalid()
{
static const pid_t invalid_pid = 0;
Process p(invalid_pid);
p.d->pid = -1;
return p;
}
Process::Process(pid_t pid)
: Signalable(pid),
d(new Private{pid})
{
if (pid < 0)
throw std::runtime_error("Cannot construct instance for invalid pid.");
}
Process::~Process() noexcept
{
}
pid_t Process::pid() const
{
return d->pid;
}
ProcessGroup Process::process_group_or_throw() const
{
pid_t pgid = ::getpgid(pid());
if (pgid == -1)
throw std::system_error(errno, std::system_category());
return ProcessGroup(pgid);
}
ProcessGroup Process::process_group(std::error_code& se) const noexcept(true)
{
pid_t pgid = ::getpgid(pid());
if (pgid == -1)
{
se = std::error_code(errno, std::system_category());
}
return ProcessGroup(pgid);
}
}
}

View file

@ -0,0 +1,47 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#include <core/posix/process_group.h>
namespace core
{
namespace posix
{
struct ProcessGroup::Private
{
pid_t id;
};
pid_t ProcessGroup::id() const
{
return d->id;
}
ProcessGroup::ProcessGroup(pid_t id)
: Signalable(-id), // We rely on ::kill to deliver signals, thus negate the id (see man 2 kill).
d(new Private{id})
{
}
ProcessGroup ProcessGroup::invalid()
{
static const pid_t invalid_pid = 1;
return ProcessGroup(invalid_pid);
}
}
}

View file

@ -0,0 +1,221 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#include <core/posix/signalable.h>
#include <poll.h>
#include <pthread.h>
#include <sys/eventfd.h>
#include <sys/signalfd.h>
#include <unistd.h>
#include <atomic>
namespace impl
{
void set_thread_signal_mask(::sigset_t* new_mask, ::sigset_t* old_mask)
{
::pthread_sigmask(SIG_BLOCK, new_mask, old_mask);
}
void set_process_signal_mask(::sigset_t* new_mask, ::sigset_t* old_mask)
{
::sigprocmask(SIG_BLOCK, new_mask, old_mask);
}
class SignalTrap : public core::posix::SignalTrap
{
public:
enum class Scope
{
process,
thread
};
enum class State
{
not_running,
running
};
SignalTrap(Scope scope, std::initializer_list<core::posix::Signal> blocked_signals)
: scope(scope),
state(State::not_running),
event_fd(::eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK))
{
if (event_fd == -1)
throw std::system_error(errno, std::system_category());
::sigemptyset(&blocked_signals_mask);
for(auto signal : blocked_signals)
::sigaddset(&blocked_signals_mask, static_cast<int>(signal));
switch (scope)
{
case Scope::process:
set_process_signal_mask(&blocked_signals_mask, &old_signals_mask);
break;
case Scope::thread:
set_thread_signal_mask(&blocked_signals_mask, &old_signals_mask);
break;
default:
break;
}
}
~SignalTrap()
{
switch (scope)
{
case Scope::process:
set_process_signal_mask(&old_signals_mask, nullptr);
break;
case Scope::thread:
set_thread_signal_mask(&old_signals_mask, nullptr);
break;
default:
break;
}
::close(event_fd);
}
bool has(core::posix::Signal signal) override
{
return ::sigismember(&blocked_signals_mask, static_cast<int>(signal));
}
void run() override
{
static constexpr int signal_fd_idx = 0;
static constexpr int event_fd_idx = 1;
static constexpr int signal_info_buffer_size = 5;
if (state.load() == State::running)
throw std::runtime_error("SignalTrap::run can only be run once.");
state.store(State::running);
// Make sure we clean up the signal fd whenever
// we leave the scope of run.
struct Scope
{
~Scope()
{
if (signal_fd != -1)
::close(signal_fd);
}
int signal_fd;
} scope{::signalfd(-1, &blocked_signals_mask, SFD_CLOEXEC | SFD_NONBLOCK)};
if (scope.signal_fd == -1)
throw std::system_error(errno, std::system_category());
pollfd fds[2];
signalfd_siginfo signal_info[signal_info_buffer_size];
for (;;)
{
fds[signal_fd_idx] = {scope.signal_fd, POLLIN, 0};
fds[event_fd_idx] = {event_fd, POLLIN, 0};
auto rc = ::poll(fds, 2, -1);
if (rc == -1)
{
if (errno == EINTR)
continue;
break;
}
if (rc == 0)
continue;
if (fds[signal_fd_idx].revents & POLLIN)
{
auto result = ::read(scope.signal_fd, signal_info, sizeof(signal_info));
for (uint i = 0; i < result / sizeof(signalfd_siginfo); i++)
{
if (has(static_cast<core::posix::Signal>(signal_info[i].ssi_signo)))
{
on_signal_raised(
static_cast<core::posix::Signal>(
signal_info[i].ssi_signo));
}
}
}
if (fds[event_fd_idx].revents & POLLIN)
{
std::int64_t value{1};
// Consciously void-ing the return value here.
// Not much we can do about an error.
auto result = ::read(event_fd, &value, sizeof(value));
(void) result;
break;
}
}
state.store(State::not_running);
}
void stop() override
{
static const std::int64_t value = {1};
if (sizeof(value) != ::write(event_fd, &value, sizeof(value)))
throw std::system_error(errno, std::system_category());
}
core::Signal<core::posix::Signal>& signal_raised() override
{
return on_signal_raised;
}
private:
Scope scope;
std::atomic<State> state;
int event_fd;
core::Signal<core::posix::Signal> on_signal_raised;
::sigset_t old_signals_mask;
::sigset_t blocked_signals_mask;
};
}
std::shared_ptr<core::posix::SignalTrap> core::posix::trap_signals_for_process(
std::initializer_list<core::posix::Signal> blocked_signals)
{
return std::make_shared<impl::SignalTrap>(
impl::SignalTrap::Scope::process,
blocked_signals);
}
std::shared_ptr<core::posix::SignalTrap> core::posix::trap_signals_for_all_subsequent_threads(
std::initializer_list<core::posix::Signal> blocked_signals)
{
return std::make_shared<impl::SignalTrap>(
impl::SignalTrap::Scope::thread,
blocked_signals);
}

View file

@ -0,0 +1,52 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#include <core/posix/signalable.h>
namespace core
{
namespace posix
{
struct Signalable::Private
{
pid_t pid;
};
Signalable::Signalable(pid_t pid) : d(new Private{pid})
{
}
void Signalable::send_signal_or_throw(Signal signal)
{
auto result = ::kill(d->pid, static_cast<int>(signal));
if (result == -1)
throw std::system_error(errno, std::system_category());
}
void Signalable::send_signal(Signal signal, std::error_code& e) noexcept
{
auto result = ::kill(d->pid, static_cast<int>(signal));
if (result == -1)
{
e = std::error_code(errno, std::system_category());
}
}
}
}

View file

@ -0,0 +1,35 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#include <core/posix/standard_stream.h>
namespace core
{
namespace posix
{
StandardStream operator|(StandardStream l, StandardStream r)
{
return static_cast<StandardStream>(static_cast<std::uint8_t>(l) | static_cast<std::uint8_t>(r));
}
StandardStream operator&(StandardStream l, StandardStream r)
{
return static_cast<StandardStream>(static_cast<std::uint8_t>(l) & static_cast<std::uint8_t>(r));
}
}
}

View file

@ -0,0 +1,177 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#include <core/posix/this_process.h>
#include <core/posix/process.h>
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <mutex>
#include <sstream>
#include <vector>
#include <cerrno>
#include <cstdlib>
#if defined(_GNU_SOURCE)
#include <unistd.h>
#else
extern char** environ;
#endif
namespace core
{
namespace posix
{
namespace this_process
{
namespace env
{
namespace
{
std::mutex& env_guard()
{
static std::mutex m;
return m;
}
}
void for_each(const std::function<void(const std::string&, const std::string&)>& functor) noexcept(true)
{
std::lock_guard<std::mutex> lg(env_guard());
auto it = ::environ;
while (it != nullptr && *it != nullptr)
{
std::string line(*it);
functor(line.substr(0,line.find_first_of('=')),
line.substr(line.find_first_of('=')+1));
++it;
}
}
std::string get_or_throw(const std::string& key)
{
std::lock_guard<std::mutex> lg(env_guard());
auto result = ::getenv(key.c_str());
if (result == nullptr)
{
std::stringstream ss;
ss << "Variable with name " << key << " is not defined in the environment";
throw std::runtime_error(ss.str());
}
return std::string{result};
}
std::string get(const std::string& key,
const std::string& default_value) noexcept(true)
{
std::lock_guard<std::mutex> lg(env_guard());
auto result = ::getenv(key.c_str());
return std::string{result ? result : default_value};
}
void unset_or_throw(const std::string& key)
{
std::lock_guard<std::mutex> lg(env_guard());
auto rc = ::unsetenv(key.c_str());
if (rc == -1)
throw std::system_error(errno, std::system_category());
}
bool unset(const std::string& key,
std::error_code& se) noexcept(true)
{
std::lock_guard<std::mutex> lg(env_guard());
auto rc = ::unsetenv(key.c_str());
if (rc == -1)
{
se = std::error_code(errno, std::system_category());
return false;
}
return true;
}
void set_or_throw(const std::string& key,
const std::string& value)
{
std::lock_guard<std::mutex> lg(env_guard());
static const int overwrite = 0;
auto rc = ::setenv(key.c_str(), value.c_str(), overwrite);
if (rc == -1)
throw std::system_error(errno, std::system_category());
}
bool set(const std::string &key,
const std::string &value,
std::error_code& se) noexcept(true)
{
std::lock_guard<std::mutex> lg(env_guard());
static const int overwrite = 0;
auto rc = ::setenv(key.c_str(), value.c_str(), overwrite);
if (rc == -1)
{
se = std::error_code(errno, std::system_category());
return false;
}
return true;
}
}
Process instance() noexcept(true)
{
static const Process self{getpid()};
return self;
}
Process parent() noexcept(true)
{
return Process(getppid());
}
std::istream& cin() noexcept(true)
{
return std::cin;
}
std::ostream& cout() noexcept(true)
{
return std::cout;
}
std::ostream& cerr() noexcept(true)
{
return std::cerr;
}
}
}
}

View file

@ -0,0 +1,33 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#include <core/posix/wait.h>
namespace core
{
namespace posix
{
namespace wait
{
Flags operator|(Flags l, Flags r)
{
return static_cast<Flags>(static_cast<std::uint8_t>(l) | static_cast<std::uint8_t>(r));
}
}
}
}

View file

@ -0,0 +1,99 @@
/*
* Copyright © 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voss <thomas.voss@canonical.com>
*/
#include <core/testing/cross_process_sync.h>
#include <system_error>
#include <poll.h>
#include <unistd.h>
namespace
{
const int read_fd = 0;
const int write_fd = 1;
}
core::testing::CrossProcessSync::CrossProcessSync() : counter(0)
{
if (::pipe(fds) < 0)
throw std::system_error(errno, std::system_category());
}
core::testing::CrossProcessSync::CrossProcessSync(const CrossProcessSync& rhs) : counter(rhs.counter)
{
fds[0] = ::dup(rhs.fds[0]);
fds[1] = ::dup(rhs.fds[1]);
}
core::testing::CrossProcessSync::~CrossProcessSync() noexcept
{
::close(fds[0]);
::close(fds[1]);
}
core::testing::CrossProcessSync& core::testing::CrossProcessSync::operator=(const core::testing::CrossProcessSync& rhs)
{
::close(fds[0]);
::close(fds[1]);
fds[0] = ::dup(rhs.fds[0]);
fds[1] = ::dup(rhs.fds[1]);
counter = rhs.counter;
return *this;
}
void core::testing::CrossProcessSync::try_signal_ready_for(const std::chrono::milliseconds& duration)
{
static const short empty_revents = 0;
pollfd poll_fd[1] = { { fds[write_fd], POLLOUT, empty_revents } };
int rc = -1;
if ((rc = ::poll(poll_fd, 1, duration.count())) < 0)
throw std::system_error(errno, std::system_category());
else if (rc == 0)
throw Error::Timeout{};
static const std::uint32_t value = 1;
if (sizeof(value) != write(fds[write_fd], std::addressof(value), sizeof(value)))
throw std::system_error(errno, std::system_category());
}
std::uint32_t core::testing::CrossProcessSync::wait_for_signal_ready_for(const std::chrono::milliseconds& duration)
{
static const short empty_revents = 0;
pollfd poll_fd[1] = { { fds[read_fd], POLLIN, empty_revents } };
int rc = -1;
if ((rc = ::poll(poll_fd, 1, duration.count())) < 0)
throw std::system_error(errno, std::system_category());
else if (rc == 0)
throw Error::Timeout{};
std::uint32_t value = 0;
if (sizeof(value) != read(fds[read_fd], std::addressof(value), sizeof(value)))
throw std::system_error(errno, std::system_category());
if (value != 1)
throw std::system_error(errno, std::system_category());
counter += value;
return counter;
}

View file

@ -0,0 +1,78 @@
/*
* Copyright © 2012-2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Thomas Voß <thomas.voss@canonical.com>
*/
#include <core/testing/fork_and_run.h>
#include <core/posix/exit.h>
#include <core/posix/fork.h>
#include <core/posix/wait.h>
core::testing::ForkAndRunResult core::testing::operator|(
core::testing::ForkAndRunResult lhs,
core::testing::ForkAndRunResult rhs)
{
return static_cast<core::testing::ForkAndRunResult>(
static_cast<unsigned int> (lhs) | static_cast<unsigned int>(rhs));
}
core::testing::ForkAndRunResult core::testing::operator&(
core::testing::ForkAndRunResult lhs,
core::testing::ForkAndRunResult rhs)
{
return static_cast<core::testing::ForkAndRunResult>(
static_cast<unsigned int> (lhs) & static_cast<unsigned int>(rhs));
}
core::testing::ForkAndRunResult core::testing::fork_and_run(
const std::function<core::posix::exit::Status()>& service,
const std::function<core::posix::exit::Status()>& client)
{
core::testing::ForkAndRunResult result = core::testing::ForkAndRunResult::empty;
auto service_process = core::posix::fork(service, core::posix::StandardStream::empty);
auto client_process = core::posix::fork(client, core::posix::StandardStream::empty);
auto client_result = client_process.wait_for(core::posix::wait::Flags::untraced);
switch (client_result.status)
{
case core::posix::wait::Result::Status::exited:
if (client_result.detail.if_exited.status == core::posix::exit::Status::failure)
result = result | core::testing::ForkAndRunResult::client_failed;
break;
default:
result = result | core::testing::ForkAndRunResult::client_failed;
break;
}
service_process.send_signal_or_throw(core::posix::Signal::sig_term);
auto service_result = service_process.wait_for(core::posix::wait::Flags::untraced);
switch (service_result.status)
{
case core::posix::wait::Result::Status::exited:
if (service_result.detail.if_exited.status == core::posix::exit::Status::failure)
result = result | core::testing::ForkAndRunResult::service_failed;
break;
default:
result = result | core::testing::ForkAndRunResult::service_failed;
break;
}
return result;
}

View file

@ -0,0 +1,16 @@
{
global:
extern "C++" {
core::*;
typeinfo?for?core::*;
typeinfo?name?for?core::*;
VTT?for?core::*;
virtual?thunk?to?core::*;
vtable?for?core::*;
std::hash*;
};
local:
extern "C++" {
*;
};
};