Calling 'ls' with execv

做~自己de王妃 提交于 2020-01-04 04:08:25

问题


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?


回答1:


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
    else
        wait( &status );        // parent: wait for the child (not really necessary)

    return 0;
}


来源:https://stackoverflow.com/questions/28507950/calling-ls-with-execv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!