I am in need of help writing a shell please. I am currently in the process of creating pipes and spawning associated child process to read and write to the pipe. The part that does not seem to work is communication between the parent and the child process. I need help with this please. First off, I would apprecia开发者_高级运维te it if you would please explain how this would work (Stdin and Stdout as well) and also help me dissect what I have to help me understand what I am missing.
The general picture is:
- You need to create a pipe, e.g. with pipe(2). The call to pipe returns a file descriptor, which must be stored in a variable.
- You call fork(2), which will duplicate your current process including the open file and the file descriptor.
- Both processes use dup2(2) to redirect stdin/out. For example, dup2(pipe, STDOUT) redirects stdout of the current process (but not the forked one!) into the pipe.
- Use execve(2) and friends to start other processes in the environment you set just up.
If you need to capture input, output and error from a child process, you need three pipes and according dup2 calls:
int in,out,err,child;
in = pipe(); out = pipe(); err = pipe();
child = fork();
if ( child == 0 ) {
dup2( in, STDIN );
dup2( out, STDOUT );
dup2( err, STDERR );
execve(something);
} else {
/* read from out and err and write into in as necessary. */
}
精彩评论