Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <errno.h>
- #include <limits.h> /* for PATH_MAX */
- #include <signal.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <unistd.h>
- enum {BASE = 10, ARGSIZE = 20, BUF_SIZE = 1024}; /* constants */
- void execute (char **args);
- void cd (char *directory);
- int killpid (char *pitstr, int sig);
- int main (void) {
- char line[BUF_SIZE] = "",
- *args[ARGSIZE],
- *delim = " \n",
- *token;
- int argIndex;
- while (1) {
- argIndex = 0; /* reinitialize variables */
- for (int i = 0; i < ARGSIZE; i++)
- args[i] = NULL;
- printf ("shell> "); /* prompt */
- if (!fgets (line, BUF_SIZE, stdin)) {
- fprintf (stderr, "Input canceled - EOF received.\n");
- return 0;
- }
- if (*line == '\n') /* Enter alone - empty line */
- continue;
- for (token = strtok (line, delim); token; token = strtok (NULL, delim))
- args[argIndex++] = token;
- if (!argIndex) continue; /* validate at least 1 arg */
- if (strcmp (args[0], "quit") == 0 || strcmp (args[0], "exit") == 0)
- break;
- /* handle 'cd' or 'kill' separately */
- if ((strcmp (args[0], "cd") == 0))
- cd (args[1]);
- else if ((strcmp (args[0], "kill") == 0)) {
- if (args[1]) killpid (args[1], SIGTERM);
- }
- else
- execute (args);
- }
- return 0;
- }
- void execute (char **args)
- {
- pid_t pid, status;
- pid = fork ();
- if (pid < 0) {
- perror ("fork");
- return;
- }
- else if (pid > 0) {
- while (wait (&status) != pid)
- continue;
- }
- else if (pid == 0) {
- if (execvp (args[0], args) == -1) {
- perror ("execvp");
- }
- _exit (EXIT_FAILURE); /* must _exit after execvp return */
- }
- }
- void cd (char *directory)
- {
- char dir[PATH_MAX] = "";
- if (!directory) { /* handle 'cd' alone */
- directory = getenv ("HOME");
- if (chdir (directory))
- fprintf (stderr, "error: chdir (%s)\n", directory);
- else
- printf ("%s\n", directory);
- return;
- }
- if (*directory == '~') { /* handle cd ~/stuff */
- strcpy (dir, getenv ("HOME"));
- strcat (dir, "/");
- strcat (dir, directory + 2);
- if (chdir (dir))
- fprintf (stderr, "error: chdir (%s)\n", dir);
- else
- printf ("%s\n", dir);
- return;
- }
- if (chdir (directory)) /* handle given directory */
- fprintf (stderr, "Failed to enter directory: %s\n", directory);
- else
- printf ("%s\n", directory);
- }
- int killpid (char *pidstr, int sig)
- {
- errno = 0; /* set errno to validate strtol conversion */
- pid_t pid = (pid_t)strtol (pidstr, NULL, BASE);
- if (errno) {
- perror ("strtol");
- return -1;
- }
- else if (pid < 1) { /* validate pid */
- fprintf (stderr, "warning: requested pid < 1, ignoring\n");
- return (int)pid;
- }
- /* temporary print of what would be done */
- printf (" killing pid '%d' with signal '%d'\n", (int)pid, sig);
- // return kill (pid, sig); /* uncomment for actual use */
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement