Why we used fork and execvp in the following program? please explain me
https://codingexpert10.blogspot.com/2022/02/write-c-program-that-behaves-like-shell.html?m=1
please explain me the code from fork why we used fork and execvp
About this post
- Posted
- Archived
- Score
- 0 · 33% up
- Kind
- Text
- ID
- zuwdhs
3 comments
Probably to make the command entered runs in a separate process. When you
fork(), you have two processes running the same line of code, but the parent will have the child PID returned while the child will receive 0 as the return value, so theif pid > 0branch is for the parent and the other branch is for the child process.execfamily replaces the process with another one, in this case it's the command to be executed.Tl;dr: Here the parent process spawn a new process and wait for it to be terminated, while the child process is replaced with the command to be executed.
ok , so in following program if i dont want to make a copy of that program , if i have to just return to the user that command he entered is wrong it will run.
This is one of question in my assignment where they asked for creation of child process. So my question is it would work just fine even if i didn't create a child process
no. processes just exit when done, so if you don't use a child then there won't be anything running to return to ( no more shell).
what would happen when the program gets done is exactly the same as "exit" in normal shells