Frage

I am studying exec family of functions.Its man page says,it replaces the current process image with a new process image. If it replaces the binary,then after returning back,how does it get the previous parameters of the process which called exec?As replacing process image means replacing all its memory sections.Please correct me if I am wrong or having less knowledge.

War es hilfreich?

Lösung

The real job is done by the execve(2) system call. All other functions (like execvp ...) are calling execve.

The execve is quite a complex system call. When successful it does not return. But the process state (including address space) has been rewritten [almost] entirely.

So basically, the address space is becoming fresh. It contains segments from the binary executable.

The program arguments, environment, etc... have been copied (at the bottom of the stack segment) into the new address space. Hence they are limited (by ARG_MAX, typically 128Kbytes -but you could raise that by recompiling your kernel).

The address space change is actually mostly done lazily (using copy on write); in reality the paging is invalidated, and subsequent accesses get pages fault, which the kernel serves by providing the new page, etc etc...

On Linux, I suggest looking into /proc/ (see proc(5) for more). In particular, try cat /proc/self/maps which will show you the address space map of the process running that cat.

Of course execve is often used after fork(2), and probably also with dup2(2) and/or pipe(2), and some waiting syscall like waitpid(2) or wait4(2), perhaps handling SIGCHLD signal -see signal(7) & sigaction(2). Please read e.g. advanced linux programming (which you can read online).

You could also consider using popen(3) or system(3) (they are calling pipe for popen, then fork & execve of /bin/sh -c ....).

Andere Tipps

A new memory block is allocated. The parameters are copied to this block. Only then are the pages from the old executable's memory freed. Note that there may be other steps in between as well. For example, the new executable is mapped into memory before the old executable is freed as well.

In Linux fork + exec is used create child process. the fork() creates the new process and exec function loads/overwrite the image/executable, given as the argument of exec(), into the process space and start executing.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top