Skip to content

Instantly share code, notes, and snippets.

@apselon
Created December 21, 2020 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apselon/3caab25f4577f8789ec49c4d7067a5b7 to your computer and use it in GitHub Desktop.
Save apselon/3caab25f4577f8789ec49c4d7067a5b7 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
enum ErrorCodes { SUCCES, BAD_INPUT, BAD_OPEN, BAD_EXEC, BAD_FORK };
enum { EXPR_LEN = 4096 };
const char* c_code_format = "#include<stdio.h>\n"
"int main(void) {\n"
" printf(\"%%d\\n\", (%s));\n"
" return 0;\n"
"}\n\0";
void remove_tmp_files(void)
{
unlink("tmp.c");
unlink("tmp.out");
}
int main(void)
{
size_t len = EXPR_LEN;
char expression[EXPR_LEN] = "";
if (NULL == fgets(expression, len, stdin)) {
return BAD_INPUT;
}
FILE* tmp_c_f = fopen("tmp.c", "w");
if (NULL == tmp_c_f) {
return BAD_OPEN;
}
fprintf(tmp_c_f, c_code_format, expression);
fclose(tmp_c_f);
pid_t compilation_pid = fork();
if (-1 == compilation_pid) {
remove_tmp_files();
return BAD_FORK;
}
else if (0 == compilation_pid) {
execlp("gcc", "gcc", "-std=c11", "tmp.c", "-o", "tmp.out", NULL);
}
else {
int compilation_status = 0;
waitpid(compilation_pid, &compilation_status, 0);
}
pid_t running_pid = fork();
if (-1 == running_pid) {
remove_tmp_files();
return BAD_FORK;
}
else if (0 == running_pid) {
execlp("./tmp.out", "tmp.out", NULL);
}
else {
int running_status = 0;
waitpid(running_pid, &running_status, 0);
remove_tmp_files();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment