Coder567
Coder567

Reputation: 51

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. What am I doing wrong? The while loop condition is only the way that it is so that it will loop forever.

Upvotes: 1

Views: 488

Answers (1)

G. Sliepen
G. Sliepen

Reputation: 7973

execvp() does not start a shell, it tries to find the binary you specify directly in the $PATH. So if you created an alias ls-l in your shell's startup scripts, then this won't work with execvp(). If you want that, use system() instead.

If you intended to execute ls -l, then you should do something like this:

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.

Upvotes: 2

Related Questions