简体   繁体   中英

Using fork and execvp in c causing error

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;
    }

execvp()传递的char**参数必须以NULL终止。

The and functions provide an array of pointers to 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 pointer. 指针终止。 Append a 0 or NULL at the end of argv* .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM