exevp skips over all code until wait call in c

时光总嘲笑我的痴心妄想 提交于 2019-12-25 01:55:30

问题


I am trying to execute a file using fork and execvp, however I am encountering some errors. I have not found any solutions to the problem I am having here online, since I don't get any errors from my exevp nor does it run. Here is my code:

 pid_t child;
    int status;
    child = fork();
    char *arg[3] = {"test","/home/ameya/Documents/computer_science/cs170/project1", (char*) 0};
    if(child == 0){
        printf("IN CHILD BEFORE EXECVP\n");
        int value = execvp(arg[0],arg);
        if(value < 0){
            printf("ERROR\n");
        }else{
            printf("In Child : %i\n", value);
        }
    }
    if(waitpid(child, &status, 0) != child){
        printf("ERROR IN PROCESS\n");
    }
    printf("In Parent\n");

When I try to run this code it only outputs the "IN CHILD BEFORE EXCEPTION" and "IN PARENT" it doesn't print out any of the printf statements in between why does it do that. The file I am trying to run a simple executable that prints "hello world" to stdout.

Thanks for any help


回答1:


From the man page:

The exec() functions only return if an error has occurred.

So, your execvp call is presumably working, and thus it is not returning.

The point of the exec functions is that they replace the currently running code with the code of another program, so it doesn't make sense that it would then return to your code once the program was done running.

Edit:

It looks like you're not calling your program correctly. I think you should be calling it like this:

char *arg[3] = {"test", (char*) 0};
int value = execvp("/home/ameya/Documents/computer_science/cs170/project1/test", arg);


来源:https://stackoverflow.com/questions/16136725/exevp-skips-over-all-code-until-wait-call-in-c

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