user93110 user93110 - 1 year ago 87
C Question

Calling 'ls' with execv

I am new to system calls and C programming and am working on my university assignment.

I want to call the 'ls' command and have it print the directory.

What I have: (I have added comments in so you can see what I see coming through each variable.

int execute( command* cmd ){

char full_path[50];
find_fullP(full_path, p_cmd);
//find_fullP successfully updates full_path to /bin/ls
char* args[p_cmd->argc];
args[0] = p_cmd->name;
int i;
for(i = 1; i < p_cmd->argc; i++){
args[i] = p_cmd->argv[i];

* this piece of code updates an args variable which holds arguments
* (stored in the struct) in case the command is something else that takes
* arguments. In this case, it will hold nothing since the command
* will be just 'ls'.

int child_process_status;
pid_t child_pid;
pid_t pid;

child_pid = fork();

if ( child_pid == 0 ) {
execv( full_path, args );
perror("fork child process error condition!" );

pid = wait( &child_process_status );
return 0;

I am not seeing anything happening and am confused, any idea?

Answer Source

Here's the minimal program that invokes ls using execv. Things to note

  • the list of args should include the executable as the first arg
  • the list of args must be NULL terminated
  • if the args are set up correctly, then args[0] can be passed as the first parameter to execv

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main( void )
    int status;
    char *args[2];

    args[0] = "/bin/ls";        // first arg is the full path to the executable
    args[1] = NULL;             // list of args must be NULL terminated

    if ( fork() == 0 )
        execv( args[0], args ); // child: call execv with the path and the args
        wait( &status );        // parent: wait for the child (not really necessary)

    return 0;