shell.c

Cod mod
mail@pastecode.io avatar
unknown
c_cpp
a month ago
1.7 kB
1
Indexable
Never

#include "stdio.h"
#include "unistd.h"
#include "sys/wait.h"
#include "string.h"

typedef unsigned Options;
const Options onBackground = 1;

// forks the process and runs the logic. Uses bit logic options
int runProcess(char *argV[], Options opts)
{

    // int fsList[2];
    // if (pipe(fsList) == -1){
    //     perror("failed to create pipe");
    // } //TODO: pipe support for operations like <, >, >>, |

    pid_t pid = fork();
    if (pid != 0)
    { // this condition will be executed by the "parent" process.
        if (pid == -1)
        {
            // fprintf(stderr,"process %s cloudn't execute",argV[0]); // let the caller of runProcess handle this.
            return -1;
        }
        
        if (opts & onBackground)
        {
            waitpid(pid, 0, WNOHANG); // do not wait the process but also notice the os, os to not make the exec process zombie after finishing
            return 0;
        }

        int exitCode;
        waitpid(pid, &exitCode, 0); // wait till end of the process via pid.
        return exitCode;
    }

    return execvp(*argV, argV); // argV should be trimmed from the & op.

    // these lines won't be accessable..
}

int main(int argC, char *argV[])
{
    if (argC == 1)
    {
        // no args
        fprintf(stderr, "%s: shell is not going to work without call args. Take an action!\n", *argV);
        return -1; // fail status code
    }
    Options opts = 0;

    if (strcmp(argV[argC - 1], "&") == 0)
    {
        printf("background");
        argV[argC - 1] = 0; // get rid of the "&" symbol.
        opts |= onBackground;
    }else printf("normal");

    

    printf("status: %i\n", runProcess(&argV[1], opts));
}