首页 > 解决方案 > C execvp 不会执行“ls -l”命令,但会执行“ls”

问题描述

#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
int flag;
void catch (int sig)
{

  if (sig == SIGINT){
  flag = 1;
  }

  if (sig == SIGHUP){
  flag == 2;
  }
}



int main ()
{
  int i;
  char *nargs[40];
  nargs[0] = "ls-l";
  signal(SIGINT, catch);
  signal(SIGHUP, catch);
  i = 2;
  while(i == 2){
   if (flag == 1){
        execvp(nargs[0],nargs);
   }
   if (flag ==2){
        execvp(nargs[1],nargs);
   }

 }
  return 0;
}

在这里,当 nargs[0] 设置为“ls-l”或“ls -l”时,它不会在 SIGINT 上执行命令,但是当 nargs[0] 设置为“ls”时,它会正常执行命令。我究竟做错了什么?while 循环条件只是它永远循环的方式。

标签: c

解决方案


execvp()不会启动 shell,它会尝试在$PATH. 因此,如果您ls-l在 shell 的启动脚本中创建了别名,那么这将不适用于execvp(). 如果需要,请system()改用。

如果您打算执行ls -l,那么您应该执行以下操作:

const char *nargs[] = {"ls", "-l", NULL};
execvp(nargs[0], nargs);

最后,如果你真的想得到一个文件列表,你不需要调用ls,你应该使用opendir()+ readdir(),或者ftw()在 POSIX 平台上。


推荐阅读