2

For an assignment, I am to write a program that will work as a command line interpreter, accepting any command, creating a new process with fork(), and using the child process to execute the command with exec(). The problem is I don't know how to use the exec() family of commands, and searching online has proven to be of little help. I am working in C++ on a Linux server at my school.

From this post, I think I want execlp(), but I am really not sure, so please correct me if I'm wrong. When I try this:

string s = "/bin/" + command;
execlp(s, command, NULL);

just to see if it works with a simple command and no arguments, like ls, I cannot even get it to compile, receiving this error:

shell.cpp:52: error: cannot convert âstd::stringâ to âconst char*â for argument â1â to âint execlp(const char*, const char*, ...)â

when attempting to pass arguments as strings. Annoyingly, our textbook does the exact same thing with string literals, and works successfully, with the statement execlp("/bin/ls", "ls", NULL);.

Clearly, I don't know how the function is meant to be used, so what I am asking is can someone offer advice or provide a resource as to which exec() I should use and how I can use it for this purpose?

Community
  • 1
  • 1
user3424612
  • 183
  • 1
  • 1
  • 9
  • 4
    Maybe reading a proper C++ book and learn about types is a good start – SwiftMango Feb 26 '15 at 01:43
  • 2
    `execlp(s, command.c_str(), NULL);` should fix the compilation error, manpages contain all information about `exec` family. – Innot Kauker Feb 26 '15 at 01:44
  • 2
    The man page explains it. See http://linux.die.net/man/3/execv – wallyk Feb 26 '15 at 01:44
  • this answer may be helpful https://stackoverflow.com/questions/1739184/how-does-one-properly-use-the-unix-exec-c-command – Kiloreux Feb 26 '15 at 01:49
  • Innot Kauker and wallyk, thank you for your responses, they are helpful. texasbruce, I did accidentally cut out the part I had about how changing them to cstrings produces errors requesting a different type for the second argument. However, changing them to cstrings again suddenly produces no compilation error. I can only think I did not transfer the files to the server at some point causing that confusion. – user3424612 Feb 26 '15 at 01:55

1 Answers1

3

In C++ string and char* (so called C-string because that's how strings are represented in C) are 2 different types.

As a quick fix (assuming command is also a string), do this:

string s = "/bin/" + command;
execlp(s.c_str(), command.c_str(), NULL);

But in the long run, you'll have to learn about strings and how to use them properly.

mmgross
  • 3,064
  • 1
  • 23
  • 32