View Full Version : unix system programming
mile1982
09-30-2004, 10:45 AM
hey there
i have to execute commands that are written on the command line in unix. i have already separated the commands into tokens but now im stuck with the problem of how to actually execute those commands.
eg: lets say the user entered " ls -l" to list all the files in a directory
pid_t pid;
if ( (pid = fork()) < 0)
fprintf(stderr,"fork error");
else if (pid == 0) { /* child */
// NOW WHAT GOES HERE ????
}
feedback would be appreciated.
thanks
mile1982
Puzzling together that this is a further development from the previous
questions you've asked.... I gave you the answer there already I think.
But well.
To execute a program after a fork you use one of the exec commands.
There are several of them that basically do the same thing, but are
different in the way you can specify things like command line and
additional environment variables.
So, look up "exec" in your man pages and see what it has to offer. There
you will also find the names of the other exec versions. As you already
stored the command line parameters in this list of yours, the right one will
be most like the execve() command.
yjkwon57
12-12-2004, 05:39 PM
I can show you three examples.
1) using execl()
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
main()
{
printf("I am process %d and about to execl an ls -l.\n",
(int) getpid());
execl("/bin/ls", "ls", "-l", NULL);
printf("This line should never be executed.\n");
}
2) using execv()
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#define MAX_ARGS 100
main()
{
char *argv[MAX_ARGS] = {
"ls",
"-l",
NULL
};
printf("I am process %d and about to execv an ls -l.\n",
(int) getpid());
execv("/bin/ls", argv);
printf("This line should never be executed.\n");
}
3) using execvp(), where the command and its arguments including the command options are to be given as the main() function arguments
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
main(int argc, char *argv[])
{
if (fork() == 0) {
execvp(argv[1], &argv[1]);
fprintf(stderr, "Could not execute %s.\n", argv[1]);
}
}
bye~~
vBulletin® v3.7.4, Copyright ©2000-2009, Jelsoft Enterprises Ltd.