init with uname

This commit is contained in:
qwjyh 2024-08-17 16:26:07 +02:00
commit 818a9f4254
4 changed files with 113 additions and 0 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
*.so

15
Makefile Normal file
View file

@ -0,0 +1,15 @@
cc = gcc
CFLAGS := $(CFLAGS) -Wall -Wextra -D_GNU_SOURCE
LIBFLAGS = $(pkg-config --libs --cflags lua)
objs = uname.so
all : $(objs)
%.so : %.c %.h
$(cc) -o $@ $(CFLAGS) $(LIBFLAGS) -fPIC -shared $<
.PHONY : clean
clean :
-rm $(objs)

81
uname.c Normal file
View file

@ -0,0 +1,81 @@
#define _GNU_SOURCE 1
#include <string.h>
#include <stdio.h>
#include <err.h>
#include <errno.h>
#include "uname.h"
#include <lauxlib.h>
#include <lua.h>
#include <sys/utsname.h>
#define ERRBUF_SIZE 1024
static int l_numid(lua_State *L) {
lua_Number x = luaL_checknumber(L, 1);
printf("%f\n", x);
lua_pushnumber(L, x);
return 1;
}
/*
* Add one
*/
long long plus_one(int x) {
return x + 1;
}
static int l_plus_one(lua_State *L) {
// argument number check is not conventional in lua?
int argc = lua_gettop(L);
if (argc != 1)
return luaL_error(L, "Invalid number of argument");
// Type check and get
lua_Integer x = luaL_checkinteger(L, 1);
lua_Integer result = plus_one(x);
// Push the result
lua_pushinteger(L, result);
// How many elements from the top is return value
return 1;
}
static int l_uname(lua_State *L) {
struct utsname name;
if (uname(&name)) {
char errbuf[ERRBUF_SIZE];
if (strerror_r(errno, errbuf, ERRBUF_SIZE))
perror("Error while making error msg");
return luaL_error(L, errbuf);
}
lua_newtable(L);
lua_pushstring(L, "sysname");
lua_pushstring(L, name.sysname);
lua_settable(L, -3);
lua_pushstring(L, "machine");
lua_pushstring(L, name.machine);
lua_settable(L, -3);
lua_pushstring(L, "release");
lua_pushstring(L, name.release);
lua_settable(L, -3);
lua_pushstring(L, "version");
lua_pushstring(L, name.version);
lua_settable(L, -3);
return 1;
}
static const struct luaL_Reg llib_uname [] = {
{"uname", l_uname},
{"numid", l_numid},
{"plusone", l_plus_one},
{NULL, NULL},
};
// for `require`
int luaopen_uname(lua_State *L) {
luaL_newlib(L, llib_uname);
return 1;
}

16
uname.h Normal file
View file

@ -0,0 +1,16 @@
#ifndef L_UNAME_H
#define L_UNAME_H
#include <sys/utsname.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
long long plus_one(int x);
static int l_numid(lua_State *L);
static int l_plus_one(lua_State *L);
static int l_uname(lua_State *L);
int luaopen_uname(lua_State *L);
#endif