使用exec在C中的其他目录中执行ls

问题描述 投票:0回答:1

标题对我想做的事情很不言自明。

我目前的尝试:

  chdir("/Path/I/want/");   //this is different that the path my program is located at
      char * ls_args[] = { "ls" , "ls -l", NULL};
      execv(ls_args[0], ls_args);
    }

我没有得到任何错误或输出,没有任何帮助吗?

c exec ls
1个回答
0
投票

Execv函数需要您必须执行的命令的完整路径。因此,除了给出"ls",您还应该通过

找出ls在系统中的位置。

$ which ls

它可能位于/ bin文件夹中。因此,您必须将"/bin/ls"赋予执行。而且,ls的任何参数都应该是数组中的另一个成员。所以不要使用

char * ls_args[] = { "ls" , "ls -l", NULL};

使用

char * ls_args[] = { "/bin/ls" , "-l", NULL};

© www.soinside.com 2019 - 2024. All rights reserved.