2

I wrote a simple C program that uses the execl function. What I'm expecting to see after running this program is the output of ps -U myusername.

If writing ps -U myusername in terminal, I get the desired result.

If calling execl("/bin/ps", "/bin/ps", "-U myusername", NULL) I get the following error message error: improper list.

However, if I remove the space from -U myusername, and call the function in the following way: execl("/bin/ps", "/bin/ps", "-Umyusername", NULL), I get the correct result.

Why is this happening and how can I achieve the expected behaviour (this is just a simple example; what I actually want is to let the user input the command and split it in command and arguments and finally call something like execlp("command", "command", "arguments", NULL).)?

Ionut Marisca
  • 257
  • 4
  • 10

1 Answers1

3

It is a variadic function. Just call it like this :

execlp("command", "command", "first arg", "second arg" /*, etc*/, NULL);

or in your case

execlp("/bin/ps", "/bin/ps", "-U", "username", NULL);

The NULL says to the function : "it is ok, there are no more arguments." If you forget it, there is an undefined behavior.

To go further : http://manpagesfr.free.fr/man/man3/stdarg.3.html

The line execlp("/bin/ps", "/bin/ps", "-Uusername", NULL); works because ps -Uusername is the same as ps -U username. Just type it in the console, it will prove you that fact ;)

The line execlp("/bin/ps", "/bin/ps", "-U username", NULL); does not work because it is as if you type ps '-U username' in your shell. '-U username' is a single argument that is not a valid argument of ps

Boiethios
  • 38,438
  • 19
  • 134
  • 183
  • Thank you! It's working. I didn't know I can call the `execl` function this way. – Ionut Marisca Apr 20 '16 at 10:12
  • You are welcome. Do not forget to validate the answer if it is ok. – Boiethios Apr 20 '16 at 10:15
  • This doesn't answer the first part of the question: *"Why is this happening"* – user694733 Apr 20 '16 at 10:17
  • 1
    It's happening because adding a space between arguments is how the shell separates arguments, but when calling a function like `execlp()` in a C program, the space is just considered a part of the one arg. In the call, *every* argument needs to be a separated, which is why calling it as `execlp(..., "-U", "username",...)` works but `"-U username"` doesn't. – detly Apr 20 '16 at 10:28