Question

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

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top