I'm on 1st year of IT Studies and I've got an exercise. I have to write my own shell for Linux using C. I have a few points to do, and one of them is my shell has to use 2-3 of shell builtin commands from man bash. How can I implement this functionality to my code? By using functions like system() or execl() or isn't it correct in this case and there are any other options?
2 Answers
(I am understanding you are asked to implement your own tiny unix shell; this is a very good but common exercise)
Most of the time, you cannot use bash builtin commands (e.g. cd, ulimit, etc...) in your own shell. And you should not use bash or /bin/sh thru system(3) but use directly fork(2), execve(2) etc..., and implement your own globbing (see glob(7)).
As an example, you have to explicitly implement some cd command (calling the chdir(2) system call) yourself in your shell. Because the current working directory is a specific property of every process (so each process has its own working directory). See also credentials(7), fork(2), execve(2).
That is why you cannot implement your cd foo by doing system("cd foo"), since system(3) starts a separate, new, /bin/sh process (and the cd foo would only chdir in that new sh process, not in yours).
Most Unix shells are free software. Feel free to study their source code. Consider also using strace(1) to understand what system calls they are doing.
Read also some book on Linux programming (e.g. ALP or something newer). See also intro(2), syscalls(2) and the man pages referenced from them.
3 Comments
sash (whose code is really small). And do spend a few hours reading relevant chapters of ALP (or any other Linux programming book). You need to learn, and to increase your skillsIf I understood your question correctly, you want to code a shell able to execute bash command in C. In that case:
You can use Execve (man execve), it is able to run bash command
You can find the path in your env. (main(int ac, char** argv, char** env))
You have to use fork() when you run a command, because execve() close your prog.
1 Comment
bash-like but a lot simpler (e.g. similar to sash)
cd,echo,exit,kill,pwd…