Search code examples
c++clinuxshellexecvp

Execvp Only runs the first command correctly


I am making a simple shell by using the fork and execvp. When I run my program and I type in a command like ls or ls -l it works just how I like it. When that gets done my program is sitting there waiting for another command, but when I put in another valid command or even putting in the same command. execvp is saying ls: cannot access 'ls': no such file or directory. I don't know why this is happening. I get the same results in running the program again. Here is my code. I can't copy it through my virtual machine so I took a picture of it.(If someone would like to edit the formating on this that would be awesome. I tried looking at the help)

https://i.sstatic.net/fq6Xo.jpg


Solution

  • The problem in your code is that you don't reset the argument counter to 0 between command launches.

    int tokenIndex=0;
    do {
    

    should be

    int tokenIndex;
    do {
      tokenIndex=0;
    

    The first time it works, but the second time you pass ls as argument of ls hence the message

    (try typing ls ls in a shell you'll get the exact same message).