If no args to main then my program should do printenv | sort | less and I've achieved that functionality. If main has arguments then the program should do printenv | grep <parameter list> | sort | less and my problem is that debugging is not working. I can try statement printf in my code and it doesn't do anything. Why? And why is the latter part of my requirement not working? What is wrong with the program?
The expected output is printenv | grep <parameter list> | sort | less. For example I would like to query the environment variables so that executing a.out JOBS COMPIZ UPSTART should be doing the same as a printenv | grep -e 'JOBS\|COMPIZ\|UPSTART' | sort | less.
Instead I get unexpected output when trying to fork a chain of commands.
#include <sys/types.h> /* definierar bland annat typen pid_t */
#include <errno.h> /* definierar felkontrollvariabeln errno */
#include <stdio.h> /* definierar stderr, dit felmeddelanden skrivs */
#include <stdlib.h> /* definierar bland annat exit() */
#include <unistd.h> /* definierar bland annat fork() */
struct command
{
const char **argv;
};
int
spawn_proc (int in, int out, struct command *cmd)
{
pid_t pid;
if ((pid = fork ()) == 0)
{
if (in != 0)
{
dup2 (in, 0);
close (in);
}
if (out != 1)
{
dup2 (out, 1);
close (out);
}
return execvp (cmd->argv [0], (char * const *)cmd->argv);
}
return pid;
}
int
fork_pipes (int n, struct command *cmd)
{
int i;
pid_t pid;
int in, fd [2];
/* The first process should get its input from the original file descriptor 0. */
in = 0;
/* Note the loop bound, we spawn here all, but the last stage of the pipeline. */
for (i = 0; i < n - 1; ++i)
{
pipe (fd);
/* f [1] is the write end of the pipe, we carry `in` from the prev iteration. */
spawn_proc (in, fd [1], cmd + i);
/* No need for the write and of the pipe, the child will write here. */
close (fd [1]);
/* Keep the read end of the pipe, the next child will read from there. */
in = fd [0];
}
/* Last stage of the pipeline - set stdin be the read end of the previous pipe
and output to the original file descriptor 1. */
if (in != 0)
dup2 (in, 0);
/* Execute the last stage with the current process. */
return execvp (cmd [i].argv [0], (char * const *)cmd [i].argv);
}
int
main (int argc, char ** argv)
{
printf("in main...");
int i;
if (argc == 1) {
const char *printenv[] = { "printenv", 0};
const char *sort[] = { "sort", 0 };
const char *less[] = { "less", 0 };
struct command cmd [] = { {printenv}, {sort}, {less} };
return fork_pipes (3, cmd);
}
if (argc > 1) {
char *tmp = argv[1];
for( i=1; i<argc-1; i++)
{
sprintf(tmp, "%s%s%s", tmp, "|", argv[i]);
}
const char *printenv[] = { "printenv", 0};
const char *grep[] = { "grep", "-E", tmp, NULL};
const char *sort[] = { "sort", 0 };
const char *less[] = { "less", 0 };
struct command cmd [] = { {printenv}, {grep}, {sort}, {less} };
return fork_pipes (4, cmd);
}
}
Part of the problem is that you are writing to a read-only memory segment by writing to argv[1] (due to the tmp = argv[1] statement). It is further aggravated by the fact that you are more than likely writing beyond the size of argv[1]. Instead you should concatenate the string to a new writable buffer of sufficient size.
To concatenate the string into the tmp variable you can use code similar to the following:
// Compute required buffer length
int len = 1; // adds 1 to the length to account for the \0 terminating char
for( i=1; i<argc; i++)
{
len += strlen(argv[i]) + 2; // +2 accounts for length of "\\|"
}
// Allocate buffer
tmp = (char*) malloc(len);
tmp[0] = '\0';
// Concatenate argument into buffer
int pos = 0;
for( i=1; i<argc; i++)
{
pos += sprintf(tmp+pos, "%s%s", (i==1?"":"|"), argv[i]);
}
printf("tmp:%s", tmp);
fflush(stdout); // force string to be printed
...
free(tmp);
As far as why the output does not appear, it is most likely due to the fact that printf is line buffered. In other words, it typically won't be printed until an end-of-line (\n) has to be printed or a fflush explicitly forces the buffer to be printed to the console.
Note: don't forget to free() the variable tmp once you are done with it.
Related
I am trying to use the execv() function.
I am trying to pass in my argument command to the left side.
execv(file,arguments);
I am using a char * to parse the incoming user input for my shell.
The second argument of execv takes a char * const*.
Is there a way I can cast a char * const to a char * const*?
I try this below,
char * arg;
char *const a[] = (char *const)arg;
error: invalid initializer
char *const a[] = (char *const)arg;
^
But it does not work and gives me errors.
Help would be apprecieated.
The error in char *const a[] = (char *const)arg; is not due to an improper conversion. It is because char *const a[] declares an array, and the initializers for an array must be in braces1, { … }, but you have specified just one initializer without braces.
Furthermore, the argv parameter to execv should be an array of pointers in which the first points to a string containing the file name of the program being executed (this is by convention, not required) and the last is a null pointer. Thus, your definition of a ought to be something like:
char * const a[] = { FileNameOfProgram, arg, NULL };
Footnote
1 Except when a string literal is used to initialize an array, but that is not the case here.
You're trying to initialize an array. Instead of doing this,
char * arg;
char *const a[] = (char *const)arg;
do this:
char * arg;
char *const a[] = {(char *const)arg};
It's quite normal to do an execv after eliminating the command name and some of the first parameters. For example, if you have some code like (you had better to post a complete and verifiable example) let's assume you are doing something like this (if you want an example, look for the xargs(1) manpage, you have a command, and after processing the options and their parameters, you want to eliminate all of them, and execute the rest as if it was a command line, e.g. I have a command to execute repeatedly a command, delaying some specified time, like:
cont -t 0.1 -- df -k .
I use <getopts.h> to process the options of my cont program, then execute repeatedly the command df -k. Options allow to show a version for the program, to specify timeout, be verbose, or the number of times to execute the command. I wrote it just now, to show you how to do it (the example includes fork(2) use, execvp(2) and redirection to capture the output of the command to be able to go back to the origin, once known the number of lines we have received, the program uses an ANSI escape to move the cursor back to the beginning.)
#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define F(_fmt) "%s:%d: " _fmt, __FILE__, __LINE__
#define FLAG_VERBOSE (1<<0)
#define FLAG_VERSION (1<<1)
#define FLAG_DELAY (1<<2)
#define FLAG_NTIMES (1<<3)
int flags = 0;
useconds_t delay = 1000000;
size_t ntimes;
void doVersion(void)
{
fprintf(stderr,
"cont: v1.0\n"
"(C) Luis Colorado. All rights reserved.\n"
"License: BSD\n");
exit(EXIT_SUCCESS);
}
ssize_t loop(int argc_unused, char **argv)
{
int fd[2];
int res = pipe(fd);
res = fork();
if (res < 0) {
fprintf(stderr,
F("fork: ERROR %d: %s\n"),
errno,
strerror(errno));
return -1;
} else if (res == 0) { /* child */
close(fd[0]); /* not going to use it */
dup2(fd[1], 1); /* redirect output to pipe */
close(fd[1]);
execvp(argv[0], argv);
fprintf(stderr,
F("execv: ERROR %d: %s\n"),
errno, strerror(errno));
return -1;
} else { /* parent */
pid_t cld_pid = res;
close(fd[1]); /* no writing to the pipe */
FILE *f = fdopen(fd[0], "rt"); /* just reading */
int c;
size_t lines = 0;
while((c = fgetc(f)) != EOF) {
if (c == '\n') lines++;
putc(c, stdout);
}
wait(NULL);
return lines;
}
} /* loop */
int main(int argc, char **argv)
{
int opt;
float t;
while ((opt = getopt(argc, argv, "t:Vvn:")) >= 0) {
switch(opt) {
case 't': flags |= FLAG_DELAY;
t = atof(optarg);
break;
case 'V': flags |= FLAG_VERSION;
break;
case 'v': flags |= FLAG_VERBOSE;
break;
case 'n': flags |= FLAG_NTIMES;
ntimes = atoi(optarg);
break;
/* ... */
}
}
if (flags & FLAG_VERSION)
doVersion();
/* the next pair of sentences is like `shift optind' in the shell. */
/* trick, don't move the parameters, just move the pointer */
argc -= optind; /* adjust the number of parameters. */
argv += optind; /* advance the pointer to the proper place */
/* NOW, argc && argv are identical to the original ones, but lacking the
* first `optind' argument strings. As the original string array ended
* in a NULL, there's no need to construct it from allocating memory.
* Anyway, we're not going to use after it's consumed in main(). */
if (flags & FLAG_VERBOSE) {
char *sep = "About to execute: ";
int i;
for (i = 0; i < argc; i++) {
fprintf(stderr, "%s%s", sep, argv[i]);
sep = " ";
}
fprintf(stderr, "\n");
}
if (flags & FLAG_DELAY) {
delay = t * 1.0E6;
}
size_t total_lines = 0;
ssize_t n = 0;
while(!(flags & FLAG_NTIMES) || ntimes--) {
/* move up as many lines as input from subcommand */
if (n) printf("\r\033[%ldA#\b", n);
n = loop(argc, argv);
if (n < 0) {
/* we have already written the error */
exit(EXIT_FAILURE);
}
usleep(delay);
total_lines += n;
}
if (flags & FLAG_VERBOSE) {
fprintf(stderr,
F("Total lines: %lu\n"),
total_lines);
}
exit(EXIT_SUCCESS);
}
you can download a complete version of this program from Github
I have Shell awk code:
awk '{sum+=$10; array[NR,1]=$11; array[NR,2]=$10; next;} END {
for (i = 1; i <= 10; i++)
printf "%3.0f'\.' %s \b '\-' %s \b '\-' %3.1f'\%' \n", i, array[i,1], array[i,2], array[i,2]/sum*100
}'
I make program on C:
int
main ()
{
const char *sort[] = { "sort", "-t", " ", "-k", "10", "-r", "-n", "log.txt", 0 };
const char *head[] = { "head", "-n 10", 0 };
const char *awk[] = { "awk", "{sum+=$10; array[NR,1]=$11; array[NR,2]=$10; next;} END { code there }", 0 };
struct command cmd [] = { {sort}, {head}, {awk} };
return fork_pipes (3, cmd);
}
I dont know how a correct to insert in argument - awk with END { loop code ... }
My task. Add to const char *awk[] = { "awk", ... }
'{sum+=$10; array[NR,1]=$11; array[NR,2]=$10; next;} END {
for (i = 1; i <= 10; i++)
printf "%3.0f'\.' %s \b '\-' %s \b '\-' %3.1f'\%' \n", i, array[i,1], array[i,2], array[i,2]/sum*100
}'
All code C:
#include <unistd.h>
struct command
{
const char **argv;
};
int
spawn_proc (int in, int out, struct command *cmd)
{
pid_t pid;
if ((pid = fork ()) == 0)
{
if (in != 0)
{
dup2 (in, 0);
close (in);
}
if (out != 1)
{
dup2 (out, 1);
close (out);
}
return execvp (cmd->argv [0], (char * const *)cmd->argv);
}
return pid;
}
int
fork_pipes (int n, struct command *cmd)
{
int i;
pid_t pid;
int in, fd [2];
/* The first process should get its input from the original file descriptor 0. */
in = 0;
/* Note the loop bound, we spawn here all, but the last stage of the pipeline. */
for (i = 0; i < n - 1; ++i)
{
pipe (fd);
/* f [1] is the write end of the pipe, we carry `in` from the prev iteration. */
spawn_proc (in, fd [1], cmd + i);
/* No need for the write and of the pipe, the child will write here. */
close (fd [1]);
/* Keep the read end of the pipe, the next child will read from there. */
in = fd [0];
}
/* Last stage of the pipeline - set stdin be the read end of the previous pipe
and output to the original file descriptor 1. */
if (in != 0)
dup2 (in, 0);
/* Execute the last stage with the current process. */
return execvp (cmd [i].argv [0], (char * const *)cmd [i].argv);
}
int
main ()
{
const char *sort[] = { "sort", "-t", " ", "-k", "10", "-r", "-n", "log.txt", 0 };
const char *head[] = { "head", "-n 10", 0 };
const char *awk[] = { "awk", "{sum+=$10; array[NR,1]=$11; array[NR,2]=$10; next;} END { code there }", 0 };
struct command cmd [] = { {sort}, {head}, {awk} };
return fork_pipes (3, cmd);
}
Assuming you don't know how to create the awk command string in C:
You can just put your awk program inline, but you have to escape all your quotes and backslashes;
Note: you can break that string into multiple lines (at least in C++, so I assume in C too):
const char* awk = "... END { "
"printf(\"%3.0f'\\.' %s \\b '\\-' %s \\b"
" '\\-' %3.1f'\\%' \\n\" "
"}";
I'm working on this command shell program and I wonder why I use malloc in one place and not the others? I use malloc for the tmpvariable, why not for the other variables? Why is it that one variable needs dynamic memory and not the others?
struct command
{
const char **argv;
};
int
spawn_proc (int in, int out, struct command *cmd)
{
pid_t pid;
if ((pid = fork ()) == 0)
{
if (in != 0)
{
dup2 (in, 0);
close (in);
}
if (out != 1)
{
dup2 (out, 1);
close (out);
}
return execvp (cmd->argv [0], (char * const *)cmd->argv);
}
return pid;
}
int
fork_pipes (int n, struct command *cmd)
{
int i;
pid_t pid;
int in, fd [2];
/* The first process should get its input from the original file descriptor 0. */
in = 0;
/* Note the loop bound, we spawn here all, but the last stage of the pipeline. */
for (i = 0; i < n - 1; ++i)
{
pipe (fd);
/* f [1] is the write end of the pipe, we carry `in` from the prev iteration. */
spawn_proc (in, fd [1], cmd + i);
/* No need for the write and of the pipe, the child will write here. */
close (fd [1]);
/* Keep the read end of the pipe, the next child will read from there. */
in = fd [0];
}
/* Last stage of the pipeline - set stdin be the read end of the previous pipe
and output to the original file descriptor 1. */
if (in != 0)
dup2 (in, 0);
/* Execute the last stage with the current process. */
return execvp (cmd [i].argv [0], (char * const *)cmd [i].argv);
}
int
main (int argc, char ** argv)
{
printf("in main...");
int i;
if (argc == 1) {
const char *printenv[] = { "printenv", 0};
const char *sort[] = { "sort", 0 };
const char *less[] = { "less", 0 };
struct command cmd [] = { {printenv}, {sort}, {less} };
return fork_pipes (3, cmd);
}
if (argc > 1) {
char *tmp;
// Compute required buffer length
int len = 1; // adds 1 to the length to account for the \0 terminating char
for( i=1; i<argc; i++)
{
len += strlen(argv[i]) + 2; // +2 accounts for length of "\\|"
}
// Allocate buffer
tmp = (char*) malloc(len);
tmp[0] = '\0';
// Concatenate argument into buffer
int pos = 0;
for( i=1; i<argc; i++)
{
pos += sprintf(tmp+pos, "%s%s", (i==1?"":"|"), argv[i]);
}
printf("tmp:%s", tmp);
fflush(stdout); // force string to be printed
const char *printenv[] = { "printenv", 0};
const char *grep[] = { "grep", "-E", tmp, NULL};
const char *sort[] = { "sort", 0 };
const char *less[] = { "less", 0 };
struct command cmd [] = { {printenv}, {grep}, {sort}, {less} };
return fork_pipes (4, cmd);
free(tmp);
}
}
Since the other pointers point to constant values, the data is already put into memory by the compiler. You cannot change them or the data they point to (the data is literal and resides in read-only memory block). The tmp variable will point into a mutable part of memory so you need to allocate it as such.
Of course you could allocate the memory statically so that you wouldn't need malloc for that either, but dynamic allocations are, as the name says, dynamic so you can allocate whatever amount you need defined run time and nor compile time. Like in this case, the amount of memory is not known while compiling.
I have a C program I am working on that takes a certain number of inputs and runs them as system commands. The rest get passed on to the shell for execution. It was suggested however, that I should try to make use of fork and exec in order to run commands. I'm stumped on how to make this happen though.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_BUFFER 1024 // max line buffer
#define MAX_ARGS 64 // max # args
#define SEPARATORS " \t\n" // token sparators
extern char **environ;
/*******************************************************************/
int main (int argc, char ** argv)
{
char linebuf[MAX_BUFFER]; // line buffer
char cmndbuf[MAX_BUFFER]; // command buffer
char * args[MAX_ARGS]; // pointers to arg strings
char ** arg; // working pointer thru args
char * prompt = "==>" ; // shell prompt
// keep reading input until "quit" command or eof of redirected input
while (!feof(stdin)) {
// get command line from input
fputs (prompt, stdout); // write prompt
fflush(stdout);
if (fgets(linebuf, MAX_BUFFER, stdin )) { // read a line
// tokenize the input into args array
arg = args;
*arg++ = strtok(linebuf,SEPARATORS); // tokenize input
while ((*arg++ = strtok(NULL,SEPARATORS)));
// last entry will be NULL
if (args[0]) { // if there's anything there
cmndbuf[0] = 0; // set zero-length command string
// check for internal/external command
if (!strcmp(args[0],"clr")) { // "clr" command
strcpy(cmndbuf, "clear");
} else
if (!strcmp(args[0],"cd"))
{
int ret;
if (!args[1])
strcpy(cmndbuf, "pwd");
ret = chdir(args[1]);
strcpy(cmndbuf, "pwd");
}else
if (!strcmp(args[0],"dir")) { // "dir" command
strcpy(cmndbuf, "ls -al ");
if (!args[1])
args[1] = "."; // if no arg set current directory
strcat(cmndbuf, args[1]);
} else
if (!strcmp(args[0],"environ")) { // "environ" command
char ** envstr = environ;
while (*envstr) { // print out environment
printf("%s\n",*envstr);
envstr++;
} // (no entry in cmndbuf)
} else
if (!strcmp(args[0],"quit")) { // "quit" command
break;
} else { // pass command on to OS shell
int i = 1;
strcpy(cmndbuf, args[0]);
while (args[i]) {
strcat(cmndbuf, " ");
strcat(cmndbuf, args[i++]);
}
}
// pass any command onto OS
if (cmndbuf[0])
system(cmndbuf);
}
}
}
return 0;
}
I am assuming you have a POSIX system, eg GNU/Linux.
This is a very common question. The first answer would be to study the implementation of system function inside free C libraries like GNU Libc. Also many good books on Unix cover this question.
As a clue, system works with fork-ing and then in the child process execve of the shell /bin/sh
An example of "system" function implementation from The UNIX Programming Environment by Brian Kernighan and Rob Pike.
#include <signal.h>
system(s) /* выполнить командную строку s */
char *s;
{
int status, pid, w, tty;
int (*istat)(), (*qstat)();
extern char *progname;
fflush(stdout);
tty = open("/dev/tty", 2);
if (tty == 1) {
fprintf(stderr, "%s: can't open /dev/tty\n", progname);
return 1;
}
if ((pid = fork()) == 0) {
close(0); dup(tty);
close(1); dup(tty);
close(2); dup(tty);
close(tty);
execlp("sh", "sh", " c", s, (char *) 0);
exit(127);
}
close(tty);
istat = signal(SIGINT, SIG_IGN);
qstat = signal(SIGQUIT, SIG_IGN);
while ((w = wait(&status)) != pid && w != 1);
if (w == 1)
status = 1;
signal(SIGINT, istat);
signal(SIGQUIT, qstat);
return status;
}
Note that the book was written before the C standard was finalized, so it does not use prototypes.
Although my program works correctly in all cases, it doesn't use a pipe to connect the output of the first of two commands to the second when they're separated by a pipe symbol. I wrote the output of the first command to a file, then redirected the standard input of the second command to the file when the process to run that command was run. I need to use a pipe system call to create the pipe and obtain the file descriptors
for the pipe, and then run the two processes at the same time. It is a homework question and I have done 99% of the work but somehow am not able to get the pipe system call working... what I've been trying is that for an input like: Command 1 | Command 2
inside the child process for command 2 I close FD[0] then dup FD[1] and for command 1 close FD[1] then dup FD[1] and close FD[0].
I am hell confused with the file descriptors when using pipe.... I have to use a pipe
Any sort of help is appreciated. Execute function is where I am forking the processes.
Here's my code...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <regex.h>
/* Global Variables */
extern char **environ; /* Environmental Variables */
char *pathList[10]; /* List of paths from the $PATH */
int pathCount; /* Count of the # of paths in $PATH */
char *pathSet; /* Variable through which $PATH is retrieved */
int hasPipe = 0;
int cmdNo = 0;
/* This function takes the 'finalPath', the full path to executable,argList[],the
full command-line input arguments and argCount, the number of arguments from
command-line as input. It the creates a child process, in turn invokes the
execve() that finally executes the executable in 'finalPath' with the arguments
in 'argText' all stored into the args[] appropriately. Child process also handles
input and output file re-direction.
*/
void execute(char *finalPath, char *argList[], int argCount)
{
int k,fd,ofound,pos,i; /* flags and temporary variables */
pid_t pid; /* process ID */
int status, which;
char msg[100];
char *args[4]; /* argument list for execve() */
int spCase = 0;
ofound = 0;
pos=0;
pid = fork(); /* Creating a new process using fork() */
if (pid == -1) /* Checking for errors in process creation */
{
write(1,"Fork failed.\n",12);
exit(1);
}
/**************************
Checking for parent process
***************************/
if (pid != 0)
{
which = wait(&status);
if (which == -1)
{
write(1,"Wait failed.\n",12);
exit(1);
}
if (status & 0xff)
{ /* Case of abnormal termination */
sprintf(msg,"ERROR: <dShell> # process %d terminated abnormally for reason %d\n",which, status & 0xff);
write(1,msg,strlen(msg));
}
else
{ /* Case of normal termination */
sprintf(msg,"process %d terminated normally with status %d\n",which, (status >> 8) & 0xff);
write(1,msg,strlen(msg));
}
}
/*************************
Checking for child process
**************************/
if (pid == 0)
{
char argText[50];
argText[0] = '\0';
int std_fd;
if(cmdNo==0 && hasPipe)
{
close(1);
std_fd = open("temp.out", O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU);
dup(std_fd);
}
else if(cmdNo==1 && hasPipe)
{
close(0);
std_fd = open("temp.out", O_RDONLY);
dup(std_fd);
}
/* Finding the first re-direction operator */
for( i = 0; i < argCount ; ++i)
{
if( ofound != 1 && ofound != 2)
{
if( strcmp(argList[i],"<") == 0 )
{
fd = open(argList[i+1],O_RDONLY);
if (fd < 0)
{
sprintf(msg,"ERROR: %s could not be opened\n", argList[i+1]);
write(1, msg, strlen(msg));
exit(5);
}
ofound = 1;
strcpy(argText,"\0");
close(0);
dup(fd);
close(fd);
}
else if(strcmp(argList[i],">") == 0)
{
fd = open(argList[i+1],O_CREAT | O_WRONLY, 0777);
pos = i;
ofound = 2;
strcpy(argText,"\0");
if (fd < 0)
{
sprintf(msg,"ERROR: %s could not be opened\n", argList[i+1]);
write(1, msg, strlen(msg));
exit(5);
}
close(1);
dup(fd);
close(fd);
}
}
}
/* If input re-direction operator is found check for an output re-direction along with it */
if(ofound == 1)
{
for( k = 0; k < argCount && ofound != 2; ++k)
{
if( strcmp(argList[k],">") == 0 )
{
fd = open(argList[k+1],O_CREAT | O_WRONLY , 0777);
spCase = 1;
ofound = 2;
strcpy(argText,"\0");
if (fd < 0)
{
sprintf(msg,"ERROR: %s could not be opened\n", argList[k+1]);
write(1, msg, strlen(msg));
exit(5);
}
close(1);
dup(fd);
close(fd);
}
}
}
/* If the re-direction operators are not found */
if( ofound == 0 )
{
for(i = 1; i < argCount; ++i)
{
strcat(argText, argList[i]);
strcat(argText, " ");
}
spCase = 2;
}
/* Case when both arguments and output re-direction operators are found */
if (spCase == 0)
{
if(pos == 0)
{
for( i = 3; i<argCount; ++i)
{
strcat(argText, argList[i]);
strcat(argText," ");
}
}
if(pos == argCount - 2)
{
for( i = 1; i<argCount - 2; ++i)
{
strcat(argText, argList[i]);
strcat(argText," ");
}
}
}
argText[strlen(argText)-1] = '\0'; /*because I added an extra space so trimming that*/
/* Running the execve */
args[0] = finalPath;
if(strlen(argText) == 0) /* checking if argText is populated */
{
args[1] = NULL;
}
else
{
args[1] = argText;
args[2] = NULL;
}
/* Execute command,if it returns that means it failed and need to display error and exit */
execve(args[0], args, environ);
sprintf(msg, "ERROR! execve() failed");
write(1, msg, strlen(msg));
}
}
/*******************************************************************************
This function checks if the path is accessible and continues to execute the
command. If the path does not exist of is not accessible, variable 'retFlag'
is used to return 0 to the calling function.
********************************************************************************/
int checkPath(char *exepath, char *argList[], int argCount, int flag)
{
char *finalPath;
int retFlag = flag;
if(access(exepath,X_OK) == 0)
{
finalPath = exepath;
retFlag = 1;
execute(finalPath,argList,argCount);
return retFlag;
}
else
return retFlag;
}
/**********************************************************************************
This function checks if the first argument is a path and if so calls checkPath().
Else it gets the paths set to the $PATH variable, tokenizes it, pads it with the
first token of input command and calls checkPath(). If the correct path is established,
the variable 'found' is used to kick out of the for loop.
************************************************************************************/
void setPath(char *argList[], int argCount)
{
char *exepath;
char com[50];
char emsg[80];
char *command;
int i,found = 0;
/* Seperating the command if redirection is used */
if( strcmp(argList[0],"<") == 0 || strcmp(argList[0],">") == 0 )
{
command = argList[2];
}
else
command = argList[0];
/* In case of no redirection, storing the commands and arguments into a array */
if(strcmp(command,"#") == 0) /* Checking for comment statements */
{
write(1,"ERROR: No command(s) found. Only comment present/n",48);
}
else
{
if(strstr(command,"/")) /* Checking if the entire path is given as a part of the command */
{
exepath = command;
found = checkPath(exepath,argList,argCount,0);
}
else /* building the path and storing it in 'com' */
{
for(i = 0; i< pathCount && found != 1; i++)
{
sprintf(com,"%s%s%s",pathList[i],"/",command);
exepath = com;
found = checkPath(exepath,argList,argCount,0);
}
}
if(found == 0)
{
sprintf(emsg,"%s%s",command,":COMMAND DOES NOT EXIST");
write(1,emsg,sizeof(emsg));
write(1,"\n",1);
}
}
}
/* Tokenizes commands into words */
void tokens(char *cmdStr)
{
char cmd[100];
strcpy(cmd,cmdStr);
char *result;
char delims[] = " , ";
char *argList[20];
int argCount = 0;
/*Tokenize the individual command into strings */
result = strtok(cmd,delims);
while( result != NULL )
{
argList[argCount] = result;
result = strtok( NULL, delims );
++argCount;
}
setPath(argList,argCount);
}
/* Tokenizes multiple commands into single commands */
void tokenize(char *inputStr)
{
int i,cmdCount = 0;
char *cmdResult;
char *cmdStr[100];
char delimiters[] = "|";
cmdResult = strtok(inputStr, delimiters);
while(cmdResult != NULL)
{
cmdStr[cmdCount]=cmdResult;
cmdResult = strtok(NULL, delimiters);
cmdCount++;
}
if( cmdCount > 1 )
hasPipe = 1;
else
hasPipe = 0;
for( i=0; i<cmdCount ; i++)
{
cmdNo = i%cmdCount;
tokens(cmdStr[i]);
}
}
int main(int argc, char *argv[])
{
char prompt[8]; /* String that stores the personalized prompt */
char *path; /* Temporary variable used for tokenization*/
char ch; /* Temporary variable used in read() */
int chCount; /* # of characters read from the prompt */
int entry; /* return variable of read() */
int flag; /* Flag to go read the next command when newline is found */
regex_t reIgnore;
char pattern[20]="^\\s*$|^#.*";
/* Tokenizing the paths asociated with the $PATH and storing them in a array declared globally */
pathCount = 0;
pathSet = getenv("PATH");
if ( !pathSet)
{
write(1, "ERROR: PATH environment does not exist.\n", 40);
exit(1);
}
path = strtok(pathSet,":");
while(path != NULL)
{
pathList[pathCount] = path;
path = strtok(NULL,":");
++pathCount;
}
/* Checks for blanks and tabs in Step 2 */
if ( regcomp(&reIgnore, pattern, REG_EXTENDED) )
{
write(1, "Error. \n",9);
exit(2);
}
sprintf(prompt,"<dShell> # "); /* Storing the personalized shell prompt into 'prompt' */
/* Reading the input from command line and passing it to tokenize() */
while(1)
{
char inputStr[100]; /* String into which inputs are read into */
chCount = 0;
flag = 0;
hasPipe = 1;
write(1,prompt,strlen(prompt)); /* Printing out the personalized shell prompt */
/* This will read a character 1 by 1 until it reaches the end of file */
entry = read(0,&ch,1);
if(!entry)
exit(0);
/* Reading the input and storing it in inputStr as long as newline is not encountered */
while( entry != 0 && flag == 0 )
{
/* A newline has been found so a new command will need to be executed */
/* The inputStr till this point is sent to tokenize() */
if( ch == '\n' )
{
inputStr[chCount] = '\0';
flag = 1;
if(chCount > 0) {
if(strcmp(inputStr,"exit") == 0)
exit(3);
else
tokenize(inputStr);
}
}
inputStr[chCount] = ch;
chCount++;
if(flag == 0)
entry = read( 0, &ch, 1 );
}
}
}
See the man page for pipe(2). It has this example:
#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int
main(int argc, char *argv[])
{
int pipefd[2];
pid_t cpid;
char buf;
assert(argc == 2);
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { /* Child reads from pipe */
close(pipefd[1]); /* Close unused write end */
while (read(pipefd[0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);
write(STDOUT_FILENO, "\n", 1);
close(pipefd[0]);
_exit(EXIT_SUCCESS);
} else { /* Parent writes argv[1] to pipe */
close(pipefd[0]); /* Close unused read end */
write(pipefd[1], argv[1], strlen(argv[1]));
close(pipefd[1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
}
}