[core] refactor test server startup

This commit is contained in:
Konstantin Käfer
2015-10-28 16:51:13 +01:00
parent c80c823da2
commit b9452bcbba
2 changed files with 27 additions and 17 deletions

View File

@@ -15,7 +15,6 @@ namespace mbgl {
namespace test {
pid_t startServer(const char *executable) {
const std::string parent_pid = std::to_string(getpid());
int pipefd[2];
if (pipe(pipefd)) {
@@ -24,19 +23,17 @@ pid_t startServer(const char *executable) {
pid_t pid = fork();
if (pid < 0) {
throw std::runtime_error("Cannot create server process");
Log::Error(Event::Setup, "Cannot create server process");
exit(1);
} else if (pid == 0) {
close(STDIN_FILENO);
if (dup(pipefd[1])) {
Log::Error(Event::Setup, "Failed to start server: %s", strerror(errno));
}
// This is the child process.
// Close the input side of the pipe.
close(pipefd[0]);
close(pipefd[1]);
// Launch the actual server process, with the pipe ID as the first argument.
char *args[] = { const_cast<char *>(executable),
const_cast<char *>(parent_pid.c_str()),
const_cast<char *>(std::to_string(pipefd[1]).c_str()),
nullptr };
int ret = execv(executable, args);
// This call should not return. In case execve failed, we exit anyway.
@@ -45,15 +42,26 @@ pid_t startServer(const char *executable) {
}
exit(0);
} else {
char buffer[8];
// This is the parent process.
// Wait until the server process sends something on the pipe.
if (!read(pipefd[0], buffer, sizeof(buffer))) {
throw std::runtime_error("Error reading a message from the server");
}
close(pipefd[0]);
// Close output side of the pipe.
close(pipefd[1]);
// Wait until the server process closes the handle.
char buffer[2];
ssize_t bytes = 0, total = 0;
while ((bytes = read(pipefd[0], buffer, sizeof(buffer))) != 0) {
total += bytes;
}
if (bytes < 0) {
Log::Error(Event::Setup, "Failed to start server: %s", strerror(errno));
exit(1);
}
if (total != 2 || strncmp(buffer, "OK", 2) != 0) {
Log::Error(Event::Setup, "Failed to start server");
exit(1);
}
close(pipefd[0]);
}
return pid;
}

View File

@@ -2,6 +2,7 @@
/* jshint node: true */
'use strict';
var fs = require('fs');
var express = require('express');
var app = express();
@@ -106,6 +107,7 @@ var server = app.listen(3000, function () {
if (process.argv[2]) {
// Allow the test to continue running.
process.stdin.write("Go!\n");
fs.write(+process.argv[2], 'OK');
fs.close(+process.argv[2]);
}
});