Unix 如何将dup2和叉子一起使用?
我正在学习一门操作系统课程,当你有叉子的时候,我很难用dup2重定向输入。我写这个小程序是为了试着理解它,但是我没有成功地将一个孙子的输出传递给一个孩子。我试图模仿unix命令:ps-A | wc-l。我是Unix新手,但我相信这应该算上我得到的运行进程列表中的行数。所以我的输出应该是一个数字Unix 如何将dup2和叉子一起使用?,unix,exec,fork,dup2,Unix,Exec,Fork,Dup2,我正在学习一门操作系统课程,当你有叉子的时候,我很难用dup2重定向输入。我写这个小程序是为了试着理解它,但是我没有成功地将一个孙子的输出传递给一个孩子。我试图模仿unix命令:ps-A | wc-l。我是Unix新手,但我相信这应该算上我得到的运行进程列表中的行数。所以我的输出应该是一个数字 #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <iostre
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <iostream>
using namespace std;
int main( int argc, char *argv[] ) {
char *searchArg = argv[ 1 ];
pid_t pid;
if ( ( pid = fork() ) > 0 ) {
wait( NULL );
cout << "Inside parent" << endl;
}
else if ( pid == 0 ) {
int fd1[ 2 ];
pipe( fd1 );
cout << "Inside child" << endl;
if ( pid = fork() > 0 ) {
dup2( fd1[ 0 ], 0 );
close( fd1[ 0 ] );
execlp( "/bin/wc", "-l", NULL );
}
else if ( pid == 0 ) {
cout << "Inside grand child" << endl;
execlp( "/bin/ps", "-A", NULL );
}
}
return 0;
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main(int argc,char*argv[]){
char*searchArg=argv[1];
pid_t pid;
如果((pid=fork())>0){
等待(空);
cout首先,让我们修复您的代码,以便在代码中添加多一点错误检查,并使其正常工作;将底部替换为:
else if ( pid == 0 ) {
int fd1[ 2 ];
pipe( fd1 );
cout << "Inside child" << endl;
if ( (pid = fork()) > 0 ) {
if (dup2( fd1[ 0 ] , 0 ) < 0) {
cerr << "Err dup2 in child" << endl;
}
close( fd1[ 0 ] );
close( fd1[ 1 ] ); // important; see below
// Note: /usr/bin, not /bin
execlp( "/usr/bin/wc", "wc", "-l", NULL );
cerr << "Err execing in child" << endl;
}
else if ( pid == 0 ) {
cout << "Inside grand child" << endl;
if (dup2( fd1[ 1 ] , 1 ) < 0) {
cerr << "Err dup2 in gchild" << endl;
}
close( fd1[ 0 ] );
close( fd1[ 1 ] );
execlp( "/bin/ps", "ps", "-A", NULL );
cerr << "Err execing in grandchild" << endl;
}
}
else如果(pid==0){
int-fd1[2];
管道(fd1);
丹尼尔,谢谢你清楚的解释!帮了大忙。我现在得到一个输出,它显示了行数、单词数和字符数。“-l”不应该吗参数只显示了行数?还有一个相关的问题:我正在通过puTTy通过终端访问linux机器。当我在上面执行ps-a | wc-l时,我得到结果145。我假设这意味着总共有145个进程可能正在运行。当我执行我的程序时,我得到5行。当你通过execlp in执行ps-a时一个程序,它只显示父级及其子级吗?Nm,我发现execlp(…)有N个参数对应于arg[0]、arg[1]、arg[2]…啊,对,oops。是的,它应该是execlp(“/usr/bin/wc”、“wc”、“-l”,NULL)
和类似的ps
。丹尼尔,你如何从一个管道传递到另一个管道?我相信第一个if
应该是if((pid=fork())>0)
。