Hello Daniweb,

I'm trying to create a very simple shell for practicing purposes, but i'm a little bit puzzeled about the usage of execve, the function i use to execute a file.

The code fragment underneath shows my usage:

childPID = vfork();

        if (childPID == 0)
        {
            execve(input.process, input.parameters, environ);
            printf("[!] %s.\n", strerror(errno));
            _exit(0);
        }
        else
        {
            waitpid(childPID, NULL, 0);
        }

In this example I have the parameters used use the following (strings are NULL terminated):

input.process: "ls"
input.parameters: NULL pointer.
environ: A variable defined in unistd.h with the current environment settings.

When I execute the application like this i get the following:

[!] No such file or directory.

So i decided to investigate the environment variable. One of the data contained in it is:

PATH=/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/home/MyUsername/bin

So one of the path paths in the path variable is "/bin" so I don't quite understand why "ls" doesn't work.

So then I tried the input "/bin/ls" instead of just "ls" and then the program does seem to work. So my question is: Why can't I provide a relative path when bin directories are specified in the PATH variable of the environment?

Recommended Answers

All 2 Replies

The 'e' forms pass the environment.
The 'p' forms (which you're not using) are the ones which search the PATH.

execve info/man has really good example code towards the bottom of the topic.

Here's what I did:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
	char *newargv[] = { "/bin/ls", "-l", NULL };
	char *newenviron[] = { NULL };
	char *exeprog = "/bin/ls";

	execve(exeprog, newargv, newenviron);

	exit(EXIT_FAILURE);
}

Like I said check the bottom of execve info/man for the example code...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.