-
Using execl()
In a previous discussion I was informed about the execl() function that can be used in place of system(). So what are the differences between the following:
Code:
#include <unistd.h>
int main(){
execl("C:\\WINDOWS\\NOTEPAD.EXE", 0);
return 0;
}
and
Code:
#include <iostream>
int main(){
system("C:\\WINDOWS\\NOTEPAD.EXE");
return 0;
}
What are the advantages of using execl() if any? Is it any safer to use than the dreaded system() call function?
Thoughts?
-
system() executes a new process and only gives control back to your application process when it is done.
execl() replaces the current process image. It can be used in one of two ways, I seem to believe; With and without a fork. With a fork, the execl replaces the child process allowing your main process (the parent) to continue untouched. Without fork execl() effectively replaces your parent process and you can't go back.
It all depends on what you want. But something immediately strikes your eye; execl() allows you to start a new process while keeping your parent process active and running and can be used to feed information to the parent process.
-
No fork() in Windows. And since you can't replace a process image, the Windows implementation of execl() actually starts the new process and then kills the current one.
By the way, <iostream> is wrong. For system(), you need <cstdlib>. And it's in std::.
execl() is no safer than system(). If you launch an external program, you run into the possibility that it was replaced.
-
not correct usage
Not correct usage because the compiler has no way of knowing that the last argument is actually a null pointer. So need to cast.
execl("C:\\WINDOWS\\NOTEPAD.EXE",(const char *) 0);
-
As mentioned, system() and execl() are fundamentally different. As noted, system() runs another process and returns either the exit code of the process or -1 on failure of the system call, while execl() runs the process replacing our process image, meaning we never actually return from execl()!
Quoting the Linux programmer's manual: "If any of the exec() functions returns, an error will have occurred. The return value is -1, and errno will be set to indicate the error."
-
Please do not resurrect old threads.