Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
APIsWithLua/ch6/limit_cpu.c
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
44 lines (32 sloc)
893 Bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // limit_cpu.c | |
| // | |
| #include "interpreter.h" | |
| #include "lauxlib.h" | |
| #include "lua.h" | |
| #include "lualib.h" | |
| #include <stdio.h> | |
| #include <sys/errno.h> | |
| int do_limit_instructions = 1; | |
| long instructions_per_hook = 1; // 100+ recommended. | |
| long instruction_count = 0; | |
| long instruction_count_limit = 100; | |
| void hook(lua_State *L, lua_Debug *ar) { | |
| instruction_count += instructions_per_hook; | |
| if (!do_limit_instructions) return; | |
| if (instruction_count > instruction_count_limit) { | |
| lua_pushstring(L, "exceeded allowed cpu time"); | |
| lua_error(L); | |
| } | |
| } | |
| void print_status() { | |
| printf("%ld instructions run so far\n", instruction_count); | |
| } | |
| int main() { | |
| lua_State *L = luaL_newstate(); | |
| luaL_openlibs(L); | |
| lua_sethook(L, hook, LUA_MASKCOUNT, instructions_per_hook); | |
| print_status(); | |
| while (accept_and_run_a_line(L)) print_status(); | |
| lua_close(L); | |
| return 0; | |
| } |