Using execvp() and fork()
Aug 14, 2011 at 9:46am UTC
For the life of me, I can't get this program to run. I tried this first on MS Visual Studio only to realize there are no fork and execvp on Windows. Then using Putty, I connected to my school's linux server, but that was no help either. I am really new to linux/unix. Input from you guys would be much appreciated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
#include <iostream>
#include <fstream>
#include <cctype>
#include <stdio.h>
#include <sys/types.h>
using namespace std;
void parse(char *line, char **argv)
{
while (*line != '\0' ) { /* if not the end of line ....... */
while (*line == ' ' || *line == '\t' || *line == '\n' )
*line++ = '\0' ; /* replace white spaces with 0 */
*argv++ = line; /* save the argument position */
while (*line != '\0' && *line != ' ' &&
*line != '\t' && *line != '\n' )
line++; /* skip the argument until ... */
}
*argv = '\0' ; /* mark the end of argument list */
}
void execute(char **argv)
{
pid_t pid;
int status;
if ((pid = fork()) < 0) { /* fork a child process */
cout << "*** ERROR: forking child process failed\n" << endl;
exit(1);
}
else if (pid == 0) { /* for the child process: */
if (execvp(*argv, argv) < 0) { /* execute the command */
cout << "*** ERROR: exec failed\n" << endl;
exit(1);
}
}
else { /* for the parent: */
while (wait(&status) != pid) /* wait for completion */
;
}
}
void main()
{
char line[1024]; /* the input line */
char *argv[64]; /* the command line argument */
while (1) { /* repeat until done .... */
cout << "tish -> " << endl; /* display a prompt */
cin.get(line); /* read in the command line */
cout << endl;
parse(line, argv); /* parse the line */
if (strcmp(argv[0], "exit" ) == 0) /* is it an "exit"? */
exit(0); /* exit if it is */
execute(argv); /* otherwise, execute the command */
}
}
Aug 14, 2011 at 12:03pm UTC
Topic archived. No new replies allowed.