gpt4 book ai didi

c - 在 C shell 中实现管道 (Unix)

转载 作者:太空狗 更新时间:2023-10-29 14:55:39 26 4
gpt4 key购买 nike

基本上我已经使用标准 POSIX 命令创建了一个 shell,我也希望能够实现管道。现在它可以正确处理命令,并且可以使用 & 进行后台处理。但我需要能够使用 | 进行管道传输和>>也是。例如这样的事情:cat 文件 1 文件 2 >> 文件 3cat 文件 1 文件 2 |更多的更多文件1 | grep 东西

这是我目前的代码。我也想避免“SYSTEM”调用。我知道你需要使用 dup2,但是我编写代码的方式有点奇怪,所以我希望有人能告诉我在这段代码中实现管道是否可行?谢谢!我知道使用了 dup2,但也使用了 im def。对如何实现 >> 以及 |

感到困惑
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>

using namespace std;


void Execute(char* command[],bool BG)
{
//Int Status is Used Purely for the waitpid, fork() is set up like normal.
int status;
pid_t pid = fork();


switch(pid)
{
case 0:
execvp(command[0], command);

if(execvp(command[0], command) == -1)
{
cout << "Command Not Found" << endl;
exit(0);
}

default:
if(BG == 0)
{
waitpid(pid, &status, 0);
//Debug cout << "DEBUG:Child Finished" << endl;
}


}

}


bool ParseArg(char* prompt, char* command[], char Readin[],bool BG)
{

fprintf(stderr, "myshell>");
cin.getline(Readin,50);
prompt = strtok(Readin, " ");
int i = 0;

while(prompt != NULL)
{
command[i] = prompt;
if(strcmp(command[i], "&") == 0){
//Debug cout << "& found";
command[i] = NULL;
return true;
}
//Debug cout << command[i] << " ";
i++;
prompt = strtok(NULL, " ");

}
return false;
}

void Clean(char* command[])
{
//Clean Array
for(int a=0; a < 50; a++)
{
command[a] = NULL;
}
}



int main()
{
char* prompt;
char* command[50];
char Readin[50];
bool BG = false;



while(command[0] != NULL)
{

Clean(command);
BG = ParseArg(prompt, command, Readin, BG);
if(strcmp(command[0], "exit") == 0 || strcmp(command[0], "quit") == 0 )
{
break;
}

else
{
Execute(command,BG);
}

}

return 1;

}

最佳答案

实际上,管道和重定向是不同的。要实现重定向(例如 >>>),您确实必须使用 dup2。首先,打开带有适当标志的所需文件(对于 >>>,它们将是 O_WRONLY|O_CREAT|O_APPEND)。其次,使用 dup2,使 stdout(文件描述符 1)成为这个新打开的 fd 的副本。最后关闭新打开的fd。

要创建管道,您需要一个pipe 系统调用。阅读它的联机帮助页,它包含示例代码。然后,您还需要 dup2 使 pipe 返回的文件描述符分别成为一个进程的标准输入和另一个进程的标准输出。

关于c - 在 C shell 中实现管道 (Unix),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3930339/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com