guts
guts

Reputation: 381

execute commands with options in a c program

I'm trying to execute a commande with arguments in a c program. For example when the user execute my program with: "./a.out ls -la"

The program should execute ls with the la options.

But I don't know how to do that.

My program use a fork.

I try this way :

pid = fork();

if(pid == 0){

execvp(argv[1], &argv[2]);

}else{

wait(NULL);

}

But it does not work.

I want to pass as a second argument of execvp the array with the args passing in the command but i'm a little confuse with pointers (and so more with pointer of pointers :s) .

I know this souldn't work because of the dash in arguments but even if I don't use the dash, the program only launch the 'ls' without taking care of the 'la' options.

If someone could help me I would be happy to know the good way to do.

Thank you.

Upvotes: 0

Views: 246

Answers (2)

JeremyP
JeremyP

Reputation: 86651

Several problems here.

  1. you do not handle the case where fork() fails.

  2. you do not handle the case where execvp() fails. If you print strerror(errno) it might give you a clue as to why your exec is failing.

  3. execvp() takes an array of char* const which must have NULL as its last element. Also, the first element should be the name of the program. This is a convention, but it does mean that, in your example the arguments are off by one. i.e. ls thinks it has been invoked with a command of -la and no arguments. I'm not sure that argv[] is guaranteed to have a NULL pointer after the end, so don't use it directly. e.g.

    char* args[3];
    args[0] = argv[1]; // You have already checked argc is at least three right?
    args[1] = argv[2];
    args[2] = NULL;
    // do your fork and error check then in the child
    
    int result = execvp(argv[1], args);
    // if you get here exec failed, handle as appropriate
    
  4. You need to check the exit valueof wait() and you should pass a legitimate int pointer so that you can diagnose any issues.

Upvotes: 0

Jim Blackler
Jim Blackler

Reputation: 23169

system

Quoth Wikipedia:

In the C standard library, system is a function used to execute subprocesses and commands. It is defined in stdlib.h header. It differs from the exec/spawn family of functions in that instead of passing arguments to an executed object, a single string is passed to the system shell, typically the POSIX shell, /bin/sh -c.

http://en.wikipedia.org/wiki/System_(C_standard_library)

Upvotes: 1

Related Questions