尝试实现我自己的Linux外壳几个基本功能,当然是时候实现管道的问题。更具体的管道工程大部分,尽管似乎放弃了最后一个论点。例如,如果我要运行命令管道在自定义的linux外壳
ps ax | grep ps
将grep命令后的ps放在我的shell中。因此,而不是输出这是使用典型的Linux外壳
339 ? S 0:00 upstart-udev-bridge --daemon
497 ? Ss 0:00 /usr/sbin/cupsd -F
503 ? S< 0:00 [kpsmoused]
720 ? S 0:00 upstart-socket-bridge --daemon
5541 pts/0 R+ 0:00 ps ax
5542 pts/0 S+ 0:00 grep --colour=auto ps
显示你得到这个
339 ? S 0:00 upstart-udev-bridge --daemon
497 ? Ss 0:00 /usr/sbin/cupsd -F
503 ? S< 0:00 [kpsmoused]
720 ? S 0:00 upstart-socket-bridge --daemon
5557 pts/0 R+ 0:00 ps ax
在这种情况下你不寻找匹配模式PS。
如下
void mypipes(char* args[], int nargs)
{
pid_t pid;
int fd[2];
char* cmdargs[nargs - 2];
char* cmdargs2[nargs - 2];
int i;
int t = 0;
int count = 0;
for(i = 0; i < nargs; i++)
{
if(!strcmp(args[i], "|"))
{
//dont put into array
t = 1;
}
else if(t == 0)
{
cmdargs[i] = args[i];
count++;
}
else if(t == 1)
{
cmdargs2[i - 3] = args[i];
}
}
if(count == 2)
{
pipe(fd);
pid = fork();
if(pid == -1)
{
perror("unable to fork");
exit(1);
}
if(pid > 0)
{
wait(&pid);
close(fd[1]);
close(0);
dup2(fd[0],0);
execlp(cmdargs2[0], cmdargs2[0], cmdargs2[1], NULL);
}
if(pid == 0)
{
close(fd[0]);
close(1);
dup2(fd[1],1);
execlp(cmdargs[0], cmdargs[0], cmdargs[1], NULL);
}
}
if(count == 1)
{
pipe(fd);
pid = fork();
if(pid == -1)
{
perror("unable to fork");
exit(1);
}
if(pid > 0)
{
wait(&pid);
close(fd[1]);
close(0);
dup2(fd[0],0);
execlp(cmdargs2[0], cmdargs2[1], NULL);
}
if(pid == 0)
{
close(fd[0]);
close(1);
dup2(fd[1],1);
execlp(cmdargs[0], cmdargs[1], NULL);
}
}
}
我检查,看看是否管后,所有的变数仍然是第二组参数中,他们是问题的管道运行的作用不是主要的,但我正在执行实际管道的地方,它不会读到最后。
非常感谢您提供有关可能出现错误的提示。