承接上篇进度,在完成 Compiler 编译模块、Runner 运行模块的底层能力后,本轮重点完成两件事:一是向下补齐公共工具层的文件读写、唯一文件名生成等基础能力;二是 对CPU 时间、内存空间的资源进行限制,信号编号做可读化映射**,** 三是向上封装 CompileAndRun 整合层,以 JSON 作为标准化输入输出协议,将代码写入、编译、运行、结果封装、资源清理全链路串成统一接口,编译服务正式具备对外提供服务的能力。
一、公共模块 util.hpp 能力扩充
本轮在原有路径管理、文件存在性检测、秒级时间戳的基础上,新增4个工具函数,全部为上层整合流程做底层支撑。
1.1 毫秒级时间戳 getTimeMS
设计思路 :原秒级时间戳粒度过粗,同一秒内的多份提交无法 通过时间戳做区分,因此补充毫秒级时间戳,作为唯一文件名的组成部分之一。 实现基于 Linux 系统调用 gettimeofday,它可同时返回秒数与微秒数,通过单位换算合并为毫秒级时间戳。
cpp
static std::string getTimeMS() // 毫秒
{
struct timeval tv;
gettimeofday(&tv, nullptr);
return std::to_string((tv.tv_sec * 1000) + (tv.tv_usec / 1000));
}
代码说明: tv.tv_sec 是秒级时间戳,乘以1000转为毫秒;tv.tv_usec 是微秒数,除以1000取整得到毫秒部分,两者相加即为总毫秒数。
1.2 全局唯一文件名生成 uniqueFileName
设计思路 :编译服务是多用户并发场景,必须保证每次请求生成的临时文件名全局唯一,否则不同用户的源文件、可执行文件、结果文件会互相覆盖,导致结果错乱。 采用「毫秒级时间戳 + 原子性递增ID」的无锁方案,在保证唯一性的同时兼顾并发性能。
原子变量核心说明:
- 头文件依赖 :需要引入
头文件,使用 std::atomic_uint定义无符号原子整型。- 核心特性 :函数内的++静态原子++ 变量在整个程序中++只有一份实例++,
id++是原子操作,多线程并发执行自增时不会出现竞态条件,++不需要额外加互斥锁,性能远高于锁方案++。- 组合规则 :最终文件名格式为 **毫秒时间戳_自增id** ,时间戳保证跨毫秒的唯一性,原子ID保证同一毫秒内的唯一性,两者结合实现全局唯一。
cpp
static std::string uniqueFileName()
{
// 通过[毫秒级时间戳+原子性递增唯一值]:来保证文件名是唯一的
static std::atomic_uint id(0);
id++;
std::string ms = TimeUtil::getTimeMS();
std::string uniq_id = std::to_string(id);
return ms + "_" + uniq_id;
}
1.3 文件写入 writeFile
设计思路 :用户提交的代码是字符串形式,必须先写入磁盘生成 .cpp 源文件,才能调用 g++ 进行编译。封装统一的写入接口,屏蔽文件打开、关闭的细节。
cpp
static bool writeFile(const std::string &targetName, const std::string &context)
{
std::ofstream out(targetName);
if (!out.is_open())
{
return false;
}
out.write(context.c_str(), context.size());
out.close();
return true;
}
**代码说明:**以输出流方式打开目标文件,打开失败直接返回 false;写入指定长度的字符串内容后关闭文件,返回写入结果。
1.4 文件读取 readFile
设计思路 :编译错误信息、程序标准输出、标准错误都存储在临时文件中,最终需要读取内容封装到返回结果里,因此提供通用的文件读取工具。 参数 keep 是可选参数,默认值为 true,控制读取时是否保留每行末尾的换行符:默认保留以完整还原程序输出格式,特殊场景可传入 false 去除换行。
cpp
static bool readFile(const std::string &targetName, std::string &context, bool keep = true)
{
context.clear();
std::ifstream in(targetName);
if (!in.is_open())
{
return false;
}
std::string temp;
while (getline(in, temp))
{
context += temp;
context+=(keep?"\n":"");
}
in.close();
return true;
}
代码说明: 先清空输出型参数 context,按行读取文件内容;根据 keep 参数决定每行末尾是否追加换行符,读取完成后关闭文件。
二、核心整合模块 CompileAndRun 实现
新增 compile_run.hpp,是编译服务对外的统一入口,内部整合 Compiler 与 Runner 两个模块,对外仅暴露一个 start 接口。输入输出均为 JSON 字符串,彻底屏蔽底层编译、运行、文件操作的所有细节。
2.1 模块定位与状态码约定
模块核心职责:
- 解析输入 JSON,提取用户代码、运行限制参数
- 生成唯一临时文件名,将用户代码写入源文件
- 依次调用编译、运行能力
- 将状态码映射为可读的错误描述,封装标准输出/错误
- 清理本次请求产生的所有临时文件
统一状态码约定,覆盖全流程所有可能的结果:
| 状态码范围 | 含义 |
|---|---|
| = 0 | 编译、运行全流程执行成功 |
| < 0 | 流程内部错误(代码为空、编译失败、内部异常等) |
| > 0 | 用户程序运行异常,值为触发进程终止的信号编号 |
2.2 状态码语义映射:code2desc
设计思路:原始状态码和信号编号不具备可读性,无法直接返回给前端。通过该函数将状态码转换为人类可读的错误描述,编译错误还会自动读取错误文件的具体内容。
cpp
static std::string code2desc(int status_code,const std::string& fileName)
{
std::string desc;
switch(status_code)
{
case 0:
desc="编译运行成功";
break;
case -1:
desc="提交代码为空";
break;
case -2:
desc="未知错误";
break;
case -3:
FileUtil::readFile(PathUtil::compile_err(fileName),desc);//编译时发生的错误
break;
case SIGABRT://6号信号
desc="超过运行内存范围";
break;
case SIGFPE://8号信号
desc="浮点数异常";
break;
case SIGXCPU://24
desc="超过cpu运行时间范围";
break;
default:
desc="未处理的状态码,status: "+std::to_string(status_code);
break;
}
return desc;
}
代码说明:
- 内部错误直接返回固定描述文本
- 编译错误(-3)会调用
readFile读取.compile_err文件,将具体的编译报错信息作为描述返回- 运行时信号对应具体的异常场景:
SIGABRT对应内存超限触发异常终止,SIGFPE对应除零等浮点数错误,SIGXCPU对应CPU运行超时- 未定义的状态码返回原始数值,便于排查问题
2.3 临时文件清理:removeTempFile
设计思路:每次请求都会生成6个临时文件,若不清理会持续占用磁盘空间。在每次请求处理完成、结果读取完毕后,统一删除所有临时文件。
cpp
static void removeTempFile(const std::string& fileName)
{
std::string _src=PathUtil::src(fileName);
if(FileUtil::existFile(_src)) unlink(_src.c_str());
std::string _exe=PathUtil::exe(fileName);
if(FileUtil::existFile(_exe)) unlink(_exe.c_str());
std::string _compile_err=PathUtil::compile_err(fileName);
if(FileUtil::existFile(_compile_err)) unlink(_compile_err.c_str());
std::string _stdin=PathUtil::std_in(fileName);
if(FileUtil::existFile(_stdin)) unlink(_stdin.c_str());
std::string _stdout=PathUtil::std_out(fileName);
if(FileUtil::existFile(_stdout)) unlink(_stdout.c_str());
std::string _stderr=PathUtil::std_err(fileName);
if(FileUtil::existFile(_stderr)) unlink(_stderr.c_str());
}
代码说明: 遍历源文件、可执行文件、编译错误、标准输入、标准输出、标准错误6类文件,先通过 existFile 判断文件是否存在,存在则通过 Linux 系统调用 unlink 删除(头文件<unistd.h>)。
2.4 核心入口:start 函数全链路解析
start 是整个编译服务的核心入口,完整覆盖从接收请求到返回结果的全部流程。
输入输出 JSON 协议约定
输入 in_json
| 字段 | 类型 | 说明 |
|---|---|---|
| code | string | 用户提交的C++源代码 |
| input | string | 程序的标准输入内容,当前预留 |
| cpu_limit | int | CPU运行时间上限(秒) |
| mem_limit | int | 内存使用上限(KB) |
输出 out_json
| 字段 | 类型 | 说明 |
|---|---|---|
| status | int | 统一状态码 |
| reason | string | 状态对应的语义化描述 |
| stdout | string | 程序标准输出,仅运行成功时返回 |
| stderr | string | 程序标准错误,仅运行成功时返回 |
(1)JSON 输入解析
代码中同时标注了旧版与新版两种 jsoncpp 写法,当前采用新版官方推荐的 API。 旧版 API(已废弃)使用 Json::Reader + parse,官方已标记废弃,错误信息不详细,配置能力弱。 新版 API 通过 CharReaderBuilder 构建 CharReader 实例,支持指定字符串解析的起止位置,解析错误信息写入独立的错误字符串,语法校验更严格。
cpp
//老版本json读取
// Json::Value in_val;
// Json::Reader reader;
// reader.parse(in_json,in_val);
//新版本json读取
Json::Value in_val;
Json::CharReaderBuilder read_builder;
std::unique_ptr<Json::CharReader> reader(read_builder.newCharReader());
std::string parse_err;
bool parse_ok = reader->parse(in_json.c_str(), in_json.c_str() + in_json.size(), &in_val, &parse_err);
std::string code=in_val["code"].asString();
std::string input=in_val["input"].asString();
int cpu_limit=in_val["cpu_limit"].asInt();
int memo_limit=in_val["memo_limit"].asInt();
代码说明: 解析完成后,通过 asString()、asInt() 从 Json::Value 中提取对应字段的值。
(2)全流程执行逻辑
整体执行采用「提前判断错误 + goto 统一出口」的设计,所有错误分支都跳转到同一个 END 标签,避免每个分支都重复编写结果封装、文件清理的代码,保证资源清理逻辑一定会执行,也提升了代码可维护性。
第一步:空代码校验
if(code.size()==0)
{
status_code=-1;//代码为空
goto END;
}
第二步:生成唯一文件名并写入源文件
cpp
//通过[毫秒级时间戳+原子性递增唯一值]:来保证文件名是唯一的
fileName=FileUtil::uniqueFileName();//形成唯一性文件名,无路径和后缀
if(!FileUtil::writeFile(PathUtil::src(fileName),code))//写入形成临时src文件
{
status_code=-2;//未知错误
goto END;
}
第三步:调用编译模块
cpp
if(!Compiler::compile(fileName))
{
status_code=-3;//代码编译发生错误
goto END;
}
第四步:调用运行模块,处理运行结果
cpp
run_result=Runner::run(fileName,cpu_limit,memo_limit);
if(run_result<0)
{
status_code=-2;//未知错误
goto END;
}
else if(run_result>0)
{
status_code=run_result;//程序运行崩溃,返回值即信号
goto END;
}
else
{
status_code=0;//运行成功
goto END;
}
(3)统一出口与结果封装
所有分支最终汇聚到 END 标签,统一组装输出 JSON 结构。只有运行成功(状态码为0)时,才读取标准输出、标准错误文件内容填入结果。
cpp
END:
out_val["status"]=status_code;
out_val["reason"]=code2desc(status_code,fileName);
if(status_code==0)
{
//生成运行成功
std::string _stdout;
FileUtil::readFile(PathUtil::std_out(fileName),_stdout);
out_val["stdout"]=_stdout;
std::string _stderr;
FileUtil::readFile(PathUtil::std_err(fileName),_stderr);
out_val["stderr"]=_stderr;
}
(4)JSON 输出序列化
同样采用新版 StreamWriter API 替代旧版的 StyledWriter,支持自定义缩进与 UTF-8 中文输出。
cpp
//老版本json写入
// Json::StyledWriter writer;
// out_json=writer.write(out_val);
//新版本json写入
Json::StreamWriterBuilder write_builder;
write_builder["indentation"] = " "; // 缩进2空格,和StyledWriter美化效果一致
write_builder["emitUTF8"] = true; // 关键:不转义中文,直接输出utf8
std::unique_ptr<Json::StreamWriter> writer(write_builder.newStreamWriter());
std::ostringstream oss;
writer->write(out_val, &oss);
out_json = oss.str();
代码说明:
indentation配置缩进空格数,实现美化输出,等价于旧版StyledWriteremitUTF8设为true是关键配置,作用是不转义中文,直接输出 UTF-8 字符,避免中文变成 Unicode 转义序列- 最终通过
ostringstream接收序列化结果,转为字符串赋值给输出型参数out_json
(5)资源清理时机
临时文件删除放在结果组装完成之后,原因是组装结果时需要读取编译错误、标准输出、标准错误等文件的内容,必须等所有读取操作完成后再删除,避免出现文件已删除、读取失败的问题。
cpp
removeTempFile(fileName);
三、工程依赖与构建配置
3.1 jsoncpp 库安装(Ubuntu 环境)
项目使用 jsoncpp 第三方库处理 JSON 的序列化与反序列化,Ubuntu 系统下可直接通过 apt 安装开发包:
cpp
sudo apt-get update
sudo apt-get install libjsoncpp-dev
安装后头文件位于系统 include 路径的 jsoncpp/json/ 目录下,库文件位于系统库路径。
3.2 Makefile 更新与链接说明
在原有 Makefile 基础上,编译选项新增 -ljsoncpp:
cpp
compile_server:compile_server.cc
g++ -o $@ $^ -std=c++11 -ljsoncpp
.PHONY:clean
clean:
rm -f compile_server
添加原因:jsoncpp 是第三方动态库,代码中仅包含了头文件中的函数声明,编译链接阶段需要通过 -ljsoncpp 告诉链接器去链接对应的库文件,否则会出现「未定义的引用」类链接错误。
四、功能测试与结果验证
4.1 测试代码设计
compile_server.cc 中模拟用户提交行为,构造 JSON 请求并调用接口:
- 使用 Raw 字符串字面量
R"(...)"编写多行测试代码,避免引号转义- 构造 JSON 输入对象,填入代码、空输入、CPU限制1秒、内存限制4MB
- 序列化为 JSON 字符串后,调用
CompileAndRun::start接口- 打印输入 JSON 与输出 JSON,验证全链路
cpp
std::string in_json;
Json::Value in_val;
in_val["code"] = R"(#include <iostream>
int main(){
std::cout<<"hello world"<<std::endl;
std::cerr<<"this is a test code"<<std::endl;
return 0;})";
in_val["input"] = "";
in_val["cpu_limit"] = 1;
in_val["mem_limit"] = 1024 * 4;
Json::FastWriter writer;
in_json=writer.write(in_val);
std::cout<<in_json<<std::endl;
std::string out_json,fileName;
CompileAndRun::start(in_json,out_json);
std::cout<<out_json<<std::endl;
4.2 运行结果解读

从运行结果可验证全链路完全跑通:
- 控制台先打印输入的 JSON 字符串,包含完整代码与限制参数
- 日志依次输出「编译成功」「运行成功」,对应两个模块的日志埋点正常工作
- 最终输出结构化 JSON:状态码为0,reason 为「编译运行成功」,stdout 与 stderr 分别捕获到了程序打印的对应内容,中文正常显示无转义。
当前编译服务的核心功能已全部闭环,具备标准化的对外服务能力。后续可以在此基础上封装 HTTP 网络服务,将编译服务部署为独立的网络节点,为上层 OJServer 提供编译运行能力。
五、代码汇总
cpp
//util.hpp
#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/fcntl.h>
#include <sys/time.h>
#include <atomic>
#include <fstream>
namespace ns_util
{
const std::string tempPath = "./Temp/";
class PathUtil
{
public:
// 编译时
static std::string makeSuffix(const std::string &fileName, const std::string &suffix)
{
std::string completePath = tempPath;
completePath += fileName;
completePath += suffix;
return completePath;
}
static std::string src(const std::string &fileName)
{
return makeSuffix(fileName, ".cpp");
}
static std::string exe(const std::string &fileName)
{
return makeSuffix(fileName, ".exe");
}
static std::string compile_err(const std::string &fileName)
{
return makeSuffix(fileName, ".compile_err");
}
// 运行时
static std::string std_out(const std::string &fileName)
{
return makeSuffix(fileName, ".stdout");
}
static std::string std_in(const std::string &fileName)
{
return makeSuffix(fileName, ".stdin");
}
static std::string std_err(const std::string &fileName)
{
return makeSuffix(fileName, ".stderr");
}
};
class TimeUtil
{
public:
static std::string getTimeStamp() // 秒
{
struct timeval tv;
gettimeofday(&tv, nullptr);
return std::to_string(tv.tv_sec);
}
static std::string getTimeMS() // 毫秒
{
struct timeval tv;
gettimeofday(&tv, nullptr);
return std::to_string((tv.tv_sec * 1000) + (tv.tv_usec / 1000));
}
};
class FileUtil
{
public:
static bool existFile(const std::string &pathName)
{
struct stat st;
// 获取属性成功则返回true
if (stat(pathName.c_str(), &st) == 0)
{
return true;
}
return false;
}
static std::string uniqueFileName()
{
// 通过[毫秒级时间戳+原子性递增唯一值]:来保证文件名是唯一的
static std::atomic_uint id(0);
id++;
std::string ms = TimeUtil::getTimeMS();
std::string uniq_id = std::to_string(id);
return ms + "_" + uniq_id;
}
static bool writeFile(const std::string &targetName, const std::string &context)
{
std::ofstream out(targetName);
if (!out.is_open())
{
return false;
}
out.write(context.c_str(), context.size());
out.close();
return true;
}
static bool readFile(const std::string &targetName, std::string &context, bool keep = true)
{
context.clear();
std::ifstream in(targetName);
if (!in.is_open())
{
return false;
}
std::string temp;
while (getline(in, temp))
{
context += temp;
context+=(keep?"\n":"");
}
in.close();
return true;
}
};
}
cpp
//runner.hpp
#include "../Common/util.hpp"
#include "../Common/log.hpp"
#include <sys/time.h>
#include <sys/resource.h>
namespace ns_runner
{
using namespace ns_log;
using namespace ns_util;
class Runner
{
public:
Runner() {}
~Runner() {}
static void setProcLimit(int cpu_limit,int memo_limit)
{
// 设置占用CPU时长
struct rlimit cpu_rlim;
cpu_rlim.rlim_cur=cpu_limit;
cpu_rlim.rlim_max=RLIM_INFINITY;
setrlimit(RLIMIT_CPU,&cpu_rlim);
//设置占用内存大小
struct rlimit memo_rlim;
memo_rlim.rlim_cur=memo_limit*1024;
memo_rlim.rlim_max=RLIM_INFINITY;
setrlimit(RLIMIT_DATA,&memo_rlim);
//RLIMIT_DATA仅限制brk出的大小,不限制mmap出来的,仅适用简单oj,
//RLIMIT_AS可以限制这两个,但会被当成危险资源项,触发 SIGSEGV(段错误)
}
/*******************************************]
* 返回值为终止状态的信号编码
* 返回值 > 0: 程序异常,退出时收到了信号,返回值就是对应的信号编号
* 返回值 == 0: 正常运行完毕的,结果保存到了对应的临时文件中
* 返回值 < 0: 内部错误
*
* cpu_limit: 该程序运行的时候,可以使用的最大cpu资源上限
* memo_limit: 改程序运行的时候,可以使用的最大的内存大小(KB)
* *****************************************/
static int run(std::string fileName,int cpu_limit,int memo_limit)
{
/*********************************************
* 程序运行:
* 1. 代码跑完,结果正确
* 2. 代码跑完,结果不正确
* 3. 代码没跑完,有异常
* 结果正确与否:是由我们的测试用例决定的!
* run只考虑:是否正确运行完毕
*
* 一个程序在默认启动的时候
* 标准输入: 不处理(用户输入用例暂时不做处理)
* 标准输出: 程序运行完成,输出结果是什么
* 标准错误: 运行时错误信息
* *******************************************/
std::string _execute = PathUtil::exe(fileName);
std::string _stdout=PathUtil::std_out(fileName);
std::string _stdin=PathUtil::std_in(fileName);
std::string _stderr=PathUtil::std_err(fileName);
umask(0);
int _stdout_fd = open(_stdout.c_str(), O_CREAT | O_WRONLY, 0644);
int _stdin_fd = open(_stdin.c_str(), O_CREAT | O_RDONLY, 0644);
int _stderr_fd = open(_stderr.c_str(), O_CREAT | O_WRONLY, 0644);
if (_stdout_fd < 0 || _stdin_fd < 0 || _stderr_fd < 0)
{
LOG(ERROR) << "创建运行文件失败" << "\n";
return -1;
}
pid_t pid = fork();
if (pid < 0)
{
close(_stdin_fd);
close(_stdout_fd);
close(_stderr_fd);
LOG(ERROR) << "创建运行工作的子进程失败" << "\n";
return -2;
}
else if (pid == 0)
{
dup2(_stdin_fd, 0);
dup2(_stdout_fd, 1);
dup2(_stderr_fd, 2);
setProcLimit(cpu_limit,memo_limit);
execl(_execute.c_str(),_execute.c_str(),nullptr);
exit(1);
}
else
{
close(_stdin_fd);
close(_stdout_fd);
close(_stderr_fd);
int status = 0;
waitpid(pid, &status, 0);
//程序运行如果有异常一定是因为收到了信号
LOG(INFO) << "运行成功,run exitNum: " <<(status&0x7f)<< "\n";
return status & 0x7f;
}
}
};
}
cpp
//compile_run.hpp
#pragma once
#include "compiler.hpp"
#include "runner.hpp"
#include <signal.h>
#include <jsoncpp/json/json.h>
namespace ns_compile_run
{
using namespace ns_log;
using namespace ns_util;
using namespace ns_compiler;
using namespace ns_runner;
class CompileAndRun
{
public:
// code > 0 : 进程收到了信号导致异常奔溃
// code < 0 : 整个过程非运行报错(代码为空,编译报错等)
// code = 0 : 整个过程全部完成
static std::string code2desc(int status_code,const std::string& fileName)
{
std::string desc;
switch(status_code)
{
case 0:
desc="编译运行成功";
break;
case -1:
desc="提交代码为空";
break;
case -2:
desc="未知错误";
break;
case -3:
FileUtil::readFile(PathUtil::compile_err(fileName),desc);//编译时发生的错误
break;
case SIGABRT://6号信号
desc="超过运行内存范围";
break;
case SIGFPE://8号信号
desc="浮点数异常";
break;
case SIGXCPU://24
desc="超过cpu运行时间范围";
break;
default:
desc="未处理的状态码,status: "+std::to_string(status_code);
break;
}
return desc;
}
static void removeTempFile(const std::string& fileName)
{
std::string _src=PathUtil::src(fileName);
if(FileUtil::existFile(_src)) unlink(_src.c_str());
std::string _exe=PathUtil::exe(fileName);
if(FileUtil::existFile(_exe)) unlink(_exe.c_str());
std::string _compile_err=PathUtil::compile_err(fileName);
if(FileUtil::existFile(_compile_err)) unlink(_compile_err.c_str());
std::string _stdin=PathUtil::std_in(fileName);
if(FileUtil::existFile(_stdin)) unlink(_stdin.c_str());
std::string _stdout=PathUtil::std_out(fileName);
if(FileUtil::existFile(_stdout)) unlink(_stdout.c_str());
std::string _stderr=PathUtil::std_err(fileName);
if(FileUtil::existFile(_stderr)) unlink(_stderr.c_str());
}
/***************************************
* 输入:
* code: 用户提交的代码
* input: 用户给自己提交的代码对应的输入,不做处理
* cpu_limit: 时间要求
* mem_limit: 空间要求
*
* 输出:
* 必填
* status: 状态码
* reason: 请求结果
* 选填:
* stdout: 我的程序运行完的结果
* stderr: 我的程序运行完的错误结果
*
* 参数:
* in_json: {"code": "#include...", "input": "","cpu_limit":1, "mem_limit":10240//十兆,单位kb}
* out_json: {"status":"0", "reason":"","stdout":"","stderr":"",}
* ************************************/
static void start(const std::string& in_json,std::string& out_json)
{
//老版本json读取
// Json::Value in_val;
// Json::Reader reader;
// reader.parse(in_json,in_val);
//新版本json读取
Json::Value in_val;
Json::CharReaderBuilder read_builder;
std::unique_ptr<Json::CharReader> reader(read_builder.newCharReader());
std::string parse_err;
bool parse_ok = reader->parse(in_json.c_str(), in_json.c_str() + in_json.size(), &in_val, &parse_err);
std::string code=in_val["code"].asString();
std::string input=in_val["input"].asString();
int cpu_limit=in_val["cpu_limit"].asInt();
int memo_limit=in_val["memo_limit"].asInt();
Json::Value out_val;
int status_code=0;
int run_result=0;
std::string fileName;//唯一用户临时文件名
if(code.size()==0)
{
status_code=-1;//代码为空
goto END;
}
//通过[毫秒级时间戳+原子性递增唯一值]:来保证文件名是唯一的
fileName=FileUtil::uniqueFileName();//形成唯一性文件名,无路径和后缀
if(!FileUtil::writeFile(PathUtil::src(fileName),code))//写入形成临时src文件
{
status_code=-2;//未知错误
goto END;
}
if(!Compiler::compile(fileName))
{
status_code=-3;//代码编译发生错误
goto END;
}
run_result=Runner::run(fileName,cpu_limit,memo_limit);
if(run_result<0)
{
status_code=-2;//未知错误
goto END;
}
else if(run_result>0)
{
status_code=run_result;//程序运行崩溃,返回值即信号
goto END;
}
else
{
status_code=0;//运行成功
goto END;
}
END:
out_val["status"]=status_code;
out_val["reason"]=code2desc(status_code,fileName);
if(status_code==0)
{
//生成运行成功
std::string _stdout;
FileUtil::readFile(PathUtil::std_out(fileName),_stdout);
out_val["stdout"]=_stdout;
std::string _stderr;
FileUtil::readFile(PathUtil::std_err(fileName),_stderr);
out_val["stderr"]=_stderr;
}
//老版本json写入
// Json::StyledWriter writer;
// out_json=writer.write(out_val);
//新版本json写入
Json::StreamWriterBuilder write_builder;
write_builder["indentation"] = " "; // 缩进2空格,和StyledWriter美化效果一致
write_builder["emitUTF8"] = true; // 关键:不转义中文,直接输出utf8
std::unique_ptr<Json::StreamWriter> writer(write_builder.newStreamWriter());
std::ostringstream oss;
writer->write(out_val, &oss);
out_json = oss.str();
removeTempFile(fileName);
}
};
}
cpp
//compile_server.cc
#include "compile_run.hpp"
using namespace ns_compile_run;
// 编译服务要时刻进行服务,要保证不同用户传递上来的code形成唯一性的临时源文件,
// 否则多个用户之间会互相影响
int main()
{
// 通过http让客户端上传一个json string
// in_json: {"code": "#include...", "input": "","cpu_limit":1, "mem_limit":10240//十兆,单位kb}
// out_json: {"status":"0", "reason":"","stdout":"","stderr":"",}
std::string in_json;
Json::Value in_val;
in_val["code"] = R"(#include <iostream>
int main(){
std::cout<<"hello world"<<std::endl;
std::cerr<<"this is a test code"<<std::endl;
return 0;})";
in_val["input"] = "";
in_val["cpu_limit"] = 1;
in_val["mem_limit"] = 1024 * 4;
Json::FastWriter writer;
in_json=writer.write(in_val);
std::cout<<in_json<<std::endl;
std::string out_json,fileName;
CompileAndRun::start(in_json,out_json);
std::cout<<out_json<<std::endl;
return 0;
}