1

I am attempting to use fork/execvp to execute another program from within my C program. It is working, however before ls outputs the contents of my directory I am getting several hundred lines of:

ls: cannot access : No such file or directory

Followed by the correct listing of the files in the directory. I am passing to execvp:

char **argv = {"ls", "/home/school/"};
char *command = "ls";

For some reason when I use the path "/home/school" it cannot find the directory. Does anyone know why that is happening and why ls is saying it cannot access?

PID  = fork();
i = 0;
if(i == numArgs) { doneFlag = 1; }
    if (PID == 0){//child process
        execvp(command, argv);//needs error checking
    }
    else if(PID > 0){
        wait(PID, 0, 0);//wait for child process to finish execution
    }
    else if(PID == -1){
        printf("ERROR:\n");
        switch (errno){
            case EAGAIN:
         printf("Cannot fork process: System Process Limit Reached\n");
         case ENOMEM:
         printf("Cannot fork process: Out of memory\n");
        }
        return 1;
    }
4
  • 1
    maybe try char **argv = {"ls", "/home/school/", (void*)0}; ? Commented Apr 23, 2014 at 16:02
  • does (void*)0 need to be in quotes? I am getting warnings when I use (void*)0 Commented Apr 23, 2014 at 16:14
  • OT: you should add break statements in your error cases Commented Apr 23, 2014 at 16:21
  • @user1768079 (char *)0 is the correct one. Commented Apr 23, 2014 at 16:50

2 Answers 2

2

The execv and execvp functions provide an array of pointers to null-terminated strings that represent the argument list available to the new program.

The first argument should point to the file name associated with the file being executed.

The array of pointers must be terminated by a NULL pointer. Append a 0 or NULL at the end of argv*.

Sign up to request clarification or add additional context in comments.

3 Comments

the last element of argv must be NULL or (char *)0 but not '\0'
Thank you, This answer + comment answered the question for me. It is working as expected now.
Thank you @IngoLeonhardt for pointing that out. I happen to mess up pointers and strings quite easily.
2

The char** argument passed in execvp() must be terminated by NULL.

2 Comments

Do you mean the strings stored by char** or the char** itself, like the last row must be a null pointer?
@user1768079 last element in the list of char*s must be NULL. Hope this helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.