我想将which
命令作为execv
. 例如,用户键入“firefox”作为输入。它将显示带有which firefox
命令的文件路径,我想在execv
. 这是我的尝试:
int main(void)
{
//char inputBuffer[MAX_LINE]; /*buffer to hold command entered */
char *args[MAX_LINE/2 + 1]; /*command line arguments */
while (1){
char command1[50] = "which ";
char *input = args[0]; /* args[0] holds input */
strcat(command1,input);
char *const parmList[] = {input,NULL};
char buf[100]; /* will convert command to the file path */
char *str;
FILE *file;
if (NULL == (file = popen(command1, "r"))) {
perror("popen");
exit(EXIT_FAILURE);
}
while (fgets(buf, sizeof(buf), file) != NULL) {
}
pclose(file);
int count=0;
for(int m=0;m<buf[m];m++){
if(buf[m] != ' ')
count++;
}
char x5[count];
for(int t=0;t<=count;t++){
x5[t]=buf[t];
}
printf("%s\n\n\n\n",x5); /*i tried to delete spaces from 'buf'
but there is something wrong in file path the output is something like that :
(input : firefox)
usr/bin/firefox
(some weird characters)
because of weird characters execv don't get filepath correctly. I have to this
only with execv
*/
pid_t childpid;
childpid = fork();
if (childpid == -1) {
printf("error");
}
if (childpid == 0) {
execv(x5, parmList);
}
}
}