I am writing a Shell in C language. User should be able to execute various commands and use pipe(|) to redirect input of one command to the other. The main shell process is the parent process and forks new process for each command and in child process the command is called by exec*() function.
我正在用C语言编写Shell。用户应该能够执行各种命令并使用管道(|)将一个命令的输入重定向到另一个命令。主shell进程是父进程,并为每个命令分配新进程,在子进程中,该命令由exec *()函数调用。
But I can't figure out how to redirect the Standard input/output of one child process to the other.
但我无法弄清楚如何将一个子进程的标准输入/输出重定向到另一个进程。
1 个解决方案
#1
1
May be this can help you....
可能这可以帮助你......
int f=open(somefile, O_WRONLY | O_CREAT, S_IRWXU);
dup2(f,1); //redirecting output to file
//execute your first command here using fork
close(f);
int f=open(somefile, O_RDONLY | O_CREAT, S_IRWXU);
dup2(f,0); //this will give the ouput of the first command to stdout
//i.e. the input is present for second one
//execute your second command here
close(f);
#1
1
May be this can help you....
可能这可以帮助你......
int f=open(somefile, O_WRONLY | O_CREAT, S_IRWXU);
dup2(f,1); //redirecting output to file
//execute your first command here using fork
close(f);
int f=open(somefile, O_RDONLY | O_CREAT, S_IRWXU);
dup2(f,0); //this will give the ouput of the first command to stdout
//i.e. the input is present for second one
//execute your second command here
close(f);