c++coperating-systemforkexecl

What does execl ("/bin/emacs", "/etc/fstab"); do?


for example:

int pid1 = fork();
printf("%s\n", "[1]");
int pid2 = fork();
printf("%s\n", "[2]");
if ((pid1 == 0) && (pid2 == 0)) {
    printf("%s\n", "[3]");
    execl("/bin/emacs", "/etc/fstab");
    int pid3 = fork();
    printf("%s\n", "[4]");
} else {
    printf("%s\n", "[5]");
}

What does the line actually do?

The execl family of functions replaces the current process image with a new process image.

So this program starts, just lets run through the program:

It will fork the processes into 2 with the first fork an print:

[1]
[1]

Afterwards it forks again so you have 4 processes and a print:

[2]
[2]
[2]
[2]

A child process has pid == 0. There is one child process with pid1 and one with pid2 so there will be exactly:

[3] 

And here comes the execl. What does it exactly do at this point?


Solution

  • The question drawn attention to forking new processes besides it had an intention to clarify how does the execl work. So, it is declared as:

    int execl(const char *path, const char *arg, ...);
    

    where is an unspecified pathname for the sh utility, file is the process image file, and for execvp(), where arg0, arg1, and so on correspond to the values passed to execvp() in argv[0], argv1, and so on.

    The arguments represented by arg0,... are pointers to null-terminated character strings. These strings shall constitute the argument list available to the new process image. The list is terminated by a null pointer. The argument arg0 should point to a filename string that is associated with the process being started by one of the exec functions.

    (taken from execl documentation)

    So, that means you are missing some arguments. In this case, you should be using it like:

    execl("/bin/emacs", "/bin/emacs", "/etc/fstab", (char*)NULL);
    

    This call should start emacs editor with argument /etc/fstab - which means emacs editor will be opened (if installed) with content of fstab file located in /etc/.