系统命令作为C中的变量

时间:2015-12-06 22:51:02

标签: c command system popen execv

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

            }
      }

    }

1 个答案:

答案 0 :(得分:1)

正如您所注意到的那样,两个循环试图删除作为第一个参数传递给--DROP TYPE TableType CREATE TYPE TableType AS TABLE (SomePrimaryKey_ID INT) GO --DROP FUNCTION Example CREATE FUNCTION Example( @TableName TableType READONLY) RETURNS @Test TABLE ( intcfmno INT ) AS BEGIN DECLARE @testing AS VARCHAR --<< just checking that I can still declare a variable in the funciton INSERT @Test SELECT 22 RETURN END -- testing the function DECLARE @myTable TableType INSERT INTO @myTable(SomePrimaryKey_ID) VALUES(111) --SELECT * FROM @myTable SELECT * from Example(@myTable) 的值的任何嵌入空格的一些问题

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

1)无法修剪comparison数组中的任何尾随换行符。

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

buf[]