作者:zjymeimei706 | 来源:互联网 | 2023-02-03 09:53
ImtryingtosimulateapipebehavioronUbuntusTerminal,forexamplethecommand:echohello|
I'm trying to simulate a pipe behavior on Ubuntu's Terminal, for example the command:
"echo hello | wc".
Please assume I got the tokens from stdin, handled everything correctly and now These are the commands I "received" from the user who typed them in the shell for me to handle.
I'm trying to create two processes. Using a pipe, in the first process, I point the file descriptor of the writing edge of the pipe to stdout. The second process should read into stdin with the reading edge of the pipe what execvp(..) returned.?
Here is the code I wrote:
我正在尝试模拟Ubuntu终端上的管道行为,例如命令:“echo hello | wc”。请假设我从stdin获得了令牌,正确处理了所有内容现在这些是我从shell中输入的“我收到”的命令供我处理。我正在尝试创建两个进程。使用管道,在第一个过程中,我将管道写边的文件描述符指向stdout。第二个进程应该读入带有execvp(..)返回的管道读边的stdin。这是我写的代码:
#include
#include
#include
#include
#include
#include
#include
#include
int main()
{
char* fcmd[] = {"echo", "hello", NULL};
char* scmd[] = {"wc", NULL};
pid_t pid;
int pipe_des[2];
int i;
pipe(pipe_des);
for(i = 0; i <2; i++)
{
pid = fork();
if (pid ==0)
{
switch (i)
{
case 0: // FIRST CHILD
{
dup2(pipe_des[1], STDOUT_FILENO);
close(pipe_des[0]);
execvp(fcmd[0], fcmd);
exit(0);
}
case 1: //SECOND CHILD
{
dup2(pipe_des[0], STDIN_FILENO);
close(pipe_des[1]);
execvp(scmd[0], scmd);
exit(0);
}
}
}
else if (pid <0)
exit(EXIT_FAILURE);
return EXIT_SUCCESS;
}
I get: " amirla@ubuntu:~/Desktop/os/class/ex4$ 1 1 6
"
Like it should, but why he's printing the bash cwd first? The pipe seems to work because I get what I should, according to the length of the word I'm sending with the echo command(in the main()). After that the cursor just waits on the line below for another command without showing me the bash pwd. (maybe stdin is waiting?)
I've looked in many posts on here as well as on other websites and I still can't seem to find a solution to my problem. Any help would be appreciated. Thanks in advance. Note: Please Ignore checking for errors, I've delete them to make the code shorter so assume they exist.
我得到:“amirla @ ubuntu:〜/ Desktop / os / class / ex4 $ 1 1 6”就像它应该的那样,但为什么他会先打印bash cwd?根据我使用echo命令发送的单词的长度(在main()中),管道似乎可以工作,因为我得到了我应该得到的东西。之后,光标只是在下面的行上等待另一个命令而没有向我显示bash pwd。 (也许stdin正在等待?)我在这里以及其他网站上查了很多帖子,我似乎仍无法找到问题的解决方案。任何帮助,将不胜感激。提前致谢。注意:请忽略检查错误,我删除它们以使代码更短,因此假设它们存在。
1 个解决方案