Add build script, shmd and util

Current functionality
* Executing a compile-time hardcoded command
This commit is contained in:
Dylan Lom 2021-01-14 22:46:28 +11:00
parent 7e0b7afb59
commit 2f8f675cfb
4 changed files with 114 additions and 0 deletions

5
build.sh Executable file
View File

@ -0,0 +1,5 @@
#!/usr/bin/env sh
#
#build shmd
cc -Wall -g -o shmd shmd.c util.c

44
shmd.c Normal file
View File

@ -0,0 +1,44 @@
#include "util.h"
#include <stdio.h>
#include <stdlib.h>
const char* argv0;
char* execute_command(const char* command) {
FILE *fp;
fp = popen(command, "r");
if (fp == NULL) edie("popen: ");
char* result = calloc(1, sizeof(char));
if (result == NULL) edie("calloc: ");
result[0] = '\0';
size_t bufsize = 81;
char* buf = calloc(bufsize, sizeof(char));
if (buf == NULL) edie("calloc: ");
/*
* concat allocates a new string on the heap, so free the old memory when we
* concat the next line of output.
*/
while (fgets(buf, bufsize, fp) != NULL) {
char* tmp = result;
result = concat(2, result, buf);
free(tmp);
}
free(buf);
pclose(fp);
return result;
}
char* process_shmd() {
return NULL;
}
int main(int argc, char* argv[]) {
SET_ARGV0();
char* result = execute_command("ls -1");
printf("%s", result);
return EXIT_SUCCESS;
}

57
util.c Normal file
View File

@ -0,0 +1,57 @@
#include "util.h"
#include <errno.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
extern const char* argv0;
void die(const char* fmt, ...)
{
fmt = concat(2, fmt, "\n");
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
exit(EXIT_FAILURE);
}
void edie(const char* fmt, ...)
{
fmt = concat(2, fmt, strerror(errno));
va_list ap;
die(fmt, ap);
}
void usage()
{
die("usage: %s\n", argv0);
}
char* concat(int count, ...)
{
va_list ap;
int newlen = 1;
/* Total length of all strings */
va_start(ap, count);
for (int i = 0; i < count; i++)
newlen += strlen(va_arg(ap, char*));
va_end(ap);
char *newstr = calloc(newlen, sizeof(char));
if (newstr == NULL) edie("calloc: ");
/* Concat strings into newstr */
va_start(ap, count);
for (int i = 0; i < count; i++) {
char* s = va_arg(ap, char*);
strcat(newstr, s);
}
va_end(ap);
return newstr;
}

8
util.h Normal file
View File

@ -0,0 +1,8 @@
#define SHIFT_ARGS() argv++; argc--;
#define SET_ARGV0() argv0 = argv[0]; SHIFT_ARGS();
void die(const char* fmt, ...);
void edie(const char* fmt, ...);
void usage();
char* concat(int count, ...);