ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
I would like to know how to store the result of execvp to a char array. Below is my code:
Code:
int main () {
char response[1000];
char *buffer[100];
int pid, status;
printf("Please enter the shell command: ");
scanf("%s",&response);
pid = fork();
if (pid < 0) {
printf("Unable to create child process, exiting.\n");
exit(0);
}
if (pid == 0) {
printf("I'm the child.\n");
*buffer = response;
execvp(*buffer,buffer);
printf("execvp failed\n");
}
else{
wait(&status);
exit(0);
}
}
If a client types "ls" then execvp will execute ls command and instead of displaying it to the screen I would like to save it as a string in a char array. Thanks in advance.
I understand what you're trying to achieve, but don't see an easy option for you. The program executed by execvp will place it's output on file descriptor #1 (aka, stdout). You could redirect this to a file or similar using freopen in the fork. MMap can back a file using memory mapping, I wonder if there is something in the reverse... (named pipe, perhaps?)
Perhaps something like:
Code:
char *fname="pipeXXXXXX";
mktemp(fname);
int fd=mkfifo(fname,"r");
if(!fork()){
freopen(fname,"w",stdout);
execvp(...);
} else {
//read fd into your buffer
}
This is not nice, so there's probably something much better. I just have no idea right now. Looking at the bash source code for the ` ` operator might give you some clue what I am missing.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.