Friday, December 7, 2018

The system subsystem

30 lines of code and it executeds the kernel call for an external utiity, and returns the result.  Note how it processes from linux command sequence ack into string form.  The returned result goes into args[0].

My Forth macro system can generate loinux command sequence and contro9l utilities without modification.  But the preferred method is having a shared object and the Forth can keep the utility open.

#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 // SysCall ls -l
 // returns the result in a buffer at args[0]
int SystemCall(int *argc, void * args[]) {
    int argi = *argc+1;
    char cmd[100];
    char *  data= malloc(10000);
    data[0]=0;
    cmd[0]=0;
    while( *((char *) args[argi]) != ';')  {
        strcat(cmd,(char *) args[argi]);
        strcat(cmd," ");
        argi++;
    }
    *argc += (argi+1);
    FILE * stream;
    const int max_buffer = 256;
    char buffer[max_buffer];
    //strcat(cmd," 2>&1"); // Do we want STDERR?

    stream = popen(cmd, "r");
    if (stream) {
        while (!feof(stream))
            if (fgets(buffer, max_buffer, stream) != NULL) strcat(data,buffer);
        pclose(stream);
    }
    args[0]=data;
    return 0;
}

No comments: