Question

I am currently writing my own terminal in C. I found out, that there is multiple variants of the exec() methode, that i can use. Its simple occurance lead me to use execv():

int main(int argc , char* argv[]){
    char* dir = getcwd(NULL, 0);
    char* command[] = {"echo", "Hello", "World", "!!!", NULL};
    execv(dir, command);
}

From my understanding this should work. It is compiling, but nothing happens.

Was it helpful?

Solution

The path argument to execv is supposed to be the path specification to the executable file you want to run, not just a directory as returned by getcwd. From the manpage:

The initial argument for these functions is the pathname of a file which is to be executed.

In other words, you're looking for something like:

execv ("/bin/echo", command);

The code you currently have is trying to run your current directory, something that's unlikely to end well, and something you may have noticed if you checked the return value from execv along with errno: nudge, nudge, wink, wink :-)

In terms of what to do for other programs, you simply substitute their full path name for /bin/echo.

You should also be aware that exec is a family of functions, each with slight variations.

Some allow environments to be passed, some automatically search the path for your executable (depending on the name given), and some use variable argument lists rather than arrays. If you want to use the automatic path searching, you would look into execvp rather than execv, then you don't have to worry about where the executable file is located.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top