Started work on system()

This commit is contained in:
NeGate 2022-06-08 21:59:48 -04:00
parent d873ab18ef
commit c893a5716c
5 changed files with 60 additions and 15 deletions

View File

@ -3,6 +3,8 @@
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// It's just mapped directly to HANDLE
struct FILE {
@ -83,3 +85,45 @@ void _os_file_write(void* ctx, size_t n, const char str[]) {
DWORD written = 0;
WriteFile((HANDLE) ctx, str, n, &written, NULL);
}
int system(const char* string) {
int wchars_required = MultiByteToWideChar(65001 /* UTF8 */, 0, string, -1, NULL, 0);
wchar_t* cmd_line = malloc(sizeof(L"cmd.exe ") + (wchars_required * sizeof(wchar_t)));
if (cmd_line == NULL) {
goto error;
}
memcpy(cmd_line, L"cmd.exe ", sizeof(L"cmd.exe "));
MultiByteToWideChar(65001 /* UTF8 */, 0, string, -1, cmd_line + sizeof("cmd.exe ") - 1, wchars_required);
STARTUPINFOW si = {
.cb = sizeof(STARTUPINFOW),
.dwFlags = STARTF_USESTDHANDLES,
.hStdInput = GetStdHandle(STD_INPUT_HANDLE),
.hStdError = GetStdHandle(STD_ERROR_HANDLE),
.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE)
};
PROCESS_INFORMATION pi = {};
if (!CreateProcessW(NULL, cmd_line, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
goto error;
}
// Wait until child process exits.
WaitForSingleObject(pi.hProcess, INFINITE);
DWORD exit_code;
if (!GetExitCodeProcess(pi.hProcess, &exit_code)) {
goto error;
}
// Close process and thread handles.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
free(cmd_line);
return exit_code;
error:
free(cmd_line);
return -1;
}

View File

@ -27,10 +27,9 @@ typedef double double_t;
#define FP_NORMAL 2
#define FP_SUBNORMAL 3
#define FP_ZERO 4
#define fpclassify(x) ( \
_is_float(x) ? _fpclassify_f(x) :
_is_double(x) ? _fpclassify_d(x) :
FP_NAN)
#define fpclassify(x) 0
#define isfinite(x) 0
double acos(double x);
float acosf(float x);

View File

@ -70,7 +70,7 @@ _Noreturn void exit(int status);
_Noreturn void _Exit(int status);
char *getenv(const char *name);
// _Noreturn void quick_exit(int status);
// int system(const char *string);
int system(const char *string);
const void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
// void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
// int abs(int j);

View File

@ -22,6 +22,8 @@ int data_cmp(void const *lhs, void const *rhs)
int main(void)
{
system("clang -v");
struct data key = { .nr = 3 };
struct data const *res = bsearch(&key, dat, sizeof dat / sizeof dat[0], sizeof dat[0], data_cmp);
if (res) {