Search
 
SCRIPT & CODE EXAMPLE
 

SHELL

how to make a shell in c for beginners

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>

#define PRMTSIZ 255
#define MAXARGS 63
#define EXITCMD "exit"

int main(void) {
    for (;;) {
        char input[PRMTSIZ + 1] = { 0x0 };
        char *ptr = input;
        char *args[MAXARGS + 1] = { NULL };
        int wstatus;

        // prompt
        printf("%s ", getuid() == 0 ? "#" : "$");
        fgets(input, PRMTSIZ, stdin);

        // ignore empty input
        if (*ptr == '
') continue;

        // convert input line to list of arguments
        for (int i = 0; i < sizeof(args) && *ptr; ptr++) {
            if (*ptr == ' ') continue;
            if (*ptr == '
') break;
            for (args[i++] = ptr; *ptr && *ptr != ' ' && *ptr != '
'; ptr++);
            *ptr = '';
        }

        // built-in: exit
        if (strcmp(EXITCMD, args[0]) == 0) return 0;

        // fork child and execute program
        signal(SIGINT, SIG_DFL);
        if (fork() == 0) exit(execvp(args[0], args));
        signal(SIGINT, SIG_IGN);

        // wait for program to finish and print exit status
        wait(&wstatus);
        if (WIFEXITED(wstatus)) printf("<%d>", WEXITSTATUS(wstatus));
    }
}
Comment

PREVIOUS NEXT
Code Example
Shell :: get users linux 
Shell :: ls with file size 
Shell :: Unable to install APK to device. Please make sure the Android SDK is installed and is properly configured in the Editor. 
Shell :: bash random sleep 
Shell :: git stash abort 
Shell :: git create new repo 
Shell :: pymongo.errors.ServerSelectionTimeoutError: localhost:27017 
Shell :: git user config 
Shell :: edit file terminal 
Shell :: sudo npm cache clean -f 
Shell :: git stash apply undo merge conflict 
Shell :: iis reset command 
Shell :: navigate to folder on mac 
Shell :: how to run debian on docker 
Shell :: firebase deploy with token 
Shell :: bin/sh sam: not found 
Shell :: ubuntu find filename recursive 
Shell :: install native run 
Shell :: amend commit 
Shell :: heroku upload local database 
Shell :: how to docker login with gitlab 
Shell :: ubuntu run in port 80 
Shell :: apache2 .htaccess not writable 
Shell :: how to install tar.xz file on ubuntu 
Shell :: uninstall all microsoft apps powershell 
Shell :: git merge develop to feature branch 
Shell :: keyrings arch linux 
Shell :: kubernetes exec into pod 
Shell :: How to remove local (untracked) files from the current Git working tree 
Shell :: how to install mongodb server in ubuntu 
ADD CONTENT
Topic
Content
Source link
Name
2+6 =