#include "spsh.h" /* Process a read line into a command and arguments and try to execute it */ void cmd(char *line) { char *cmd, *cmd_arg; pid_t pid; int status, cmd_argc; char *cmd_argv[MAX_ARGS]; /* First argument is always the executable file itself; we make it NULL to * start with, and then terminate the array with NULL */ cmd_argv[0] = cmd_argv[1] = NULL; cmd_argc = 1; /* Read the command as the first token of the line */ cmd = strtok(line, ARG_DELIM); /* Iterate through the remaining arguments with subsequent calls to strtok() */ while ((cmd_arg = strtok(NULL, ARG_DELIM)) != NULL) { cmd_argc++; if (cmd_argc < MAX_ARGS) { cmd_argv[cmd_argc - 1] = cmd_arg; cmd_argv[cmd_argc] = NULL; } } /* If there were too many arguments, say so */ if (cmd_argc >= MAX_ARGS) { fprintf(stderr, "Too many arguments (%u given, max is %u)\n", cmd_argc, MAX_ARGS); return; } /* Fork and try to execute it; wait until the fork is done. */ pid = fork(); if (pid == 0) { cmd_argv[0] = cmd; execvp(cmd, cmd_argv); } waitpid(pid, &status, 0); return; }