javex
javex

Reputation: 7544

Windows, fork and execv

I have received a Unix tool that I want to run / compile under Windows. After looking at it, I see it uses fork and execv among others. I now want to understand what it does and how I can realize this in Windows.

The code does more than asked here so please don't comment on whether this code makes sense.

pid = fork();
if(pid==0){
    execv("/usr/bin/java",args);
}

If I interpret this correctly, this one only does something like calling java with the arguments provided in the args array. So in Windows this could easily be realized by something like system() or CreateProcess (I did not read on how to do it, just know it can be done).

But here is my question: If I understand it correctly this code forks and calls execv because execv does not return and my program would not finish without forking it first. Is this correct?

Upvotes: 2

Views: 3631

Answers (2)

Viswesn
Viswesn

Reputation: 4880

Fork creates a child process and its pid is different from parent pid. In your code you are calling fork to run another process without closing the current (parent) process.

After calling fork and on going to child process we are calling execv(); execv() functions replaces the current process image with a new process image and it will execute java program with the args passed.

The parent process must wait for the child process to complete so that the child process will not become zombie process (child without parent)

Upvotes: 4

cnicutar
cnicutar

Reputation: 182619

execv does not return and my program would not finish without forking it first. Is this correct?

Actually your program would turn itself into the exec'd program. I.e. after the exec the new program would start executing, but the process would be the same: same PID, same few inherited properties etc.

Upvotes: 3

Related Questions