Reputation: 37
I am having an issue with the execve(). I am trying to write a simple shell program that will read input from the user using the getline() and then execute it using execve(). When i enter a command(input), i get this error message:
vagrant@ubuntu-focal:~/shell_exercises$ ./shell
#cisfun$ /bin/ls
line: /bin/ls
argv[0]: /bin/ls
Error:: No such file or directory
#cisfun$
i have tried to running the program with the path=/bin/ls, but it's not working. What am i doing wrong? Thanks in advance. here is the code:
int main(void)
{
char *line, *argv[] = { NULL, NULL }, *env[] = {NULL};
size_t len = 0;
ssize_t nread;
do {
printf("#cisfun$ ");
nread = getline(&line, &len, stdin);
if (nread == -1)
{
perror("can't read command\n");
exit(95);
}
printf("line: %s", line);
if (line == NULL)
{
printf("hello dawg");
continue;
}
else
{
argv[0] = line;
printf("argv[0]: %s", argv[0]);
if (execve(line, argv, env) == -1)
{
perror("Error:");
}
}
} while (1);
free(line);
return (0);
}
Upvotes: 0
Views: 1465
Reputation: 1
here is the code:
int main(void)
{
Read syscalls(2) and getline(3).
At least #include <stdio.h>
(mentioned in printf(3)) and #include <unistd.h>
(mentioned in execve(2); you may want to read also exec(3) and environ(7)..)
Then compile your bayer.c
source code with all warnings and debug info:
gcc -Wall -Wextra -g bayer.c -o bayershell
improve the C code to get no warnings
Then read the documentation of GCC and of GDB (the debugger) then try gdb --help
then
gdb bayershell
Be aware of proc(5) and that every shell should use fork(2) (gurus could try clone(2)...) since it needs to start processes (and later waitpid(2) for them)
You probably need to read stdio(3) then fflush(3) and tutorial slides about Linux (in French I wrote these).
In English read Advanced Linux Programming or a better book.
You probably would want to use GNU make to compile your shell project. You need to read its documentation.
You may want to use GNU indent on your source code. I recommend using a version control system like git (perhaps on github). It is helpful against mistakes (like removing a source code file), if used correctly.
What would happen if nread
is less than len
?
Consider also learning and using valgrind.
Notice that getline(3) is reading the end-of-line character. On most Linux systems, there is no file named "/bin/ls\n"
(whose name ends with the newline). You could need strchr(3) to remove the ending newline character \n
. You could even consider using GNU readline (it may reuse a previous buffer), and considering latter some autocompletion...
Today, computers use UTF8. Read about UTF8 everywhere. My (French) keyboard has keys for § and ° and your user could copy/paste ∃
from his/her web browser.
Upvotes: 1