For a project, I'm supposed to pipe the output of a command to my C program (called execute), which will then execute that command.
For example, running this: echo ls -lR /usr | ./execute
echo ls -lR /usr | ./execute
, will take the output ( ls -lR /usr
) and pass it into my C program which will then execute ls -lR /usr
.
According to the directions, I'm supposed to use execvpe()
to do the actual execution of the program, however I can't find any documentation that makes sense, nor can I get it to work without getting these errors:
execute.c: In function ‘main’:
execute.c:98: warning: implicit declaration of function ‘getenv’
execute.c:98: warning: assignment makes pointer from integer without a cast
execute.c:106: warning: implicit declaration of function ‘execvpe’
My professor said that I have to #include <unistd.h>
, and <stdio.h>
which I did, parse the input to my program (which I did), and then do this:
int main(void) {
char *path;
path = getenv("PATH");
char *envp[] = {path, NULL};
// the initialized array below could change normally.
// below is just an example
char *tests = {"ls", "-lR", NULL};
int ret = execvpe("ls", tests, envp);
if(ret == -1) { printf("error\n"); }
return 0;
}
He then stated that execvpe should find the path correctly and execute everything. But no matter what I keep getting these warnings. Running the program and ignoring the warnings immediately seg faults. Does anyone know how execvpe
works or how I can fix this?
This code should work, assuming your system has execvpe()
at all:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(void) {
char *path = getenv("PATH");
char pathenv[strlen(path) + sizeof("PATH=")];
sprintf(pathenv, "PATH=%s", path);
char *envp[] = {pathenv, NULL};
char *tests[] = {"ls", "-lR", NULL};
execvpe(tests[0], tests, envp);
fprintf(stderr, "failed to execute \"%s\"\n", tests[0]);
return 1;
}
Updated to format PATH=$PATH
in the environment.
It fixes the compilation error on tests
, uses tests[0]
as the command name to execvpe()
; it reports the error on standard error; it includes the name of the command that was not executed; it returns a failure status (non-zero) when exiting; it notes that execvpe()
only returns if it fails so it isn't necessary to test what its return status is. It does not include the system error message in the error message, but you could modify the code to include <errno.h>
and <string.h>
and use errno
and strerror()
to report that information too.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.