简体   繁体   English

C execvp 不会执行“ls -l”命令,但会执行“ls”

[英]C execvp won't execute the “ls -l” command but will execute “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;
}

Here when nargs[0] is set to "ls-l" or "ls -l" it will not execute the command on SIGINT, but when nargs[0] is set to "ls" it will execute the command just fine.在这里,当 nargs[0] 设置为“ls-l”或“ls -l”时,它不会在 SIGINT 上执行命令,但是当 nargs[0] 设置为“ls”时,它会正常执行命令。 What am I doing wrong?我究竟做错了什么? The while loop condition is only the way that it is so that it will loop forever. while 循环条件只是它永远循环的方式。

execvp() does not start a shell, it tries to find the binary you specify directly in the $PATH . execvp()不会启动 shell,它会尝试直接在$PATH中找到您指定的二进制文件。 So if you created an alias ls-l in your shell's startup scripts, then this won't work with execvp() .因此,如果您在 shell 的启动脚本中创建了别名ls-l ,那么这将不适用于execvp() If you want that, use system() instead.如果需要,请改用system()

If you intended to execute ls -l , then you should do something like this:如果您打算执行ls -l ,那么您应该执行以下操作:

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

Finally, if you really want to get a list of files, you don't need to call ls , you should use opendir() + readdir() , or alternatively ftw() on POSIX platforms.最后,如果你真的想得到一个文件列表,你不需要调用ls ,你应该使用opendir() + readdir() ,或者在 POSIX 平台上使用ftw()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM