-4

我想将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);

            }
      }

    }
4

1 回答 1

1

正如您所注意到的,这两个循环存在一些问题,它们试图删除作为第一个参数传递给的值中的任何嵌入空格execv()

assignment注意:如果不小心写了一个而不是一个comparison语句,请始终将文字放在左侧以使编译器捕获错误。

1) 未能从buf[]数组中修剪任何尾随换行符。

2)这些循环是不正确的。建议:

// remove trailing newline
char * newline = NULL;
if( NULL != (newline = strstr( buf, "\n") ) )
{ // then trim newline
    *newline = '\0';
}

// data declarations for removing space characters
char *sourceIndex = buf;
char *targetIndex = buf;

// following loop removes space characters, in place
// and stops when the string terminator char encountered
for( ; sourceIndex; sourceIndex++)  
{
    if( ' ' != *sourceIndex )
    { // then char to have in final output
        *targetIndex = *sourceIndex; // copy it
        targetIndex++;               // step to next position in target
    }
}

*targetIndex = '\0'; // terminate the (possibly shorter) string
...

// pass to new process
if( 0 == childpid )
{ // then child process
    execv(buf, parmList); // only returns if execv() failed
    perror( "execv failed" );
    exit( EXIT_FAILURE );
}
于 2015-12-06T23:44:40.237 回答