简体   繁体   English

在C中使用fork和execvp导致错误

[英]Using fork and execvp in c causing error

I am attempting to use fork/execvp to execute another program from within my C program. 我正在尝试使用fork / execvp从我的C程序中执行另一个程序。 It is working, however before ls outputs the contents of my directory I am getting several hundred lines of: 它正在工作,但是在ls输出我目录的内容之前,我得到了几百行:

ls: cannot access : No such file or directory

Followed by the correct listing of the files in the directory. 然后在目录中正确列出文件。 I am passing to execvp: 我要传递给execvp:

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

For some reason when I use the path "/home/school" it cannot find the directory. 由于某些原因,当我使用路径“ / home / school”时,找不到目录。 Does anyone know why that is happening and why ls is saying it cannot access? 有谁知道为什么会这样,为什么ls说它无法访问?

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 execv and execvp functions provide an array of pointers to null-terminated strings that represent the argument list available to the new program. execvexecvp函数提供了一个指针数组,这些指针指向以空值结尾的字符串 ,这些字符串表示新程序可用的参数列表。

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. 指针数组必须NULL指针终止。 Append a 0 or NULL at the end of argv* . argv*的末尾附加0NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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