我已经实现了C shell的开头,如下所示。到目前为止,我的重定向工作,我想我会实现|以类似的方式,但我有困难。 有人可以帮忙吗? 我将从检查管道操作符开始,然后将sa [i-1]和sa [i + 1]保存为两个单独的命令,但我不确定如何正确fork()和exec()在这之后。
int startProcess (StringArray sa)
{
int pid;
int status;
int fd1;
int fd2;
int current_in;
int current_out;
int fd0;
int fd00;
int in = 0;
int out = 0;
char input[64]="";
char output[64]="";
char cmd1[64] ="";
char cmd2[64] ="";
int fd[2];
int pipe = 0;
switch( pid = fork()){
case -1://This is an error
perror("Failure of child.");
return 1;
case 0: // This is the child
// Redirection
/* finds where '<' or '>' occurs and make that sa[i] = NULL ,
to ensure that command wont' read that*/
for(int i=0;sa[i]!='\0';i++)
{
if(strcmp(sa[i],"<")==0)
{
sa[i]=NULL;
strcpy(input,sa[i+1]);
in=2;
}
if(strcmp(sa[i],">")==0)
{
sa[i]=NULL;
strcpy(output,sa[i+1]);
out=2;
}
}
//if '<' char was found in string inputted by user
if(in)
{
// fdo is file-descriptor
int fd0;
if ((fd0 = open(input, O_RDONLY, 0)) < 0) {
perror("Couldn't open input file");
exit(0);
}
// dup2() copies content of fdo in input of preceeding file
dup2(fd0, 0); // STDIN_FILENO here can be replaced by 0
close(fd0); // necessary
}
//if '>' char was found in string inputted by user
if (out)
{
int fd00 ;
if ((fd00 = creat(output , 0644)) < 0) {
perror("Couldn't open the output file");
exit(0);
}
dup2(fd00, STDOUT_FILENO); // 1 here can be replaced by STDOUT_FILENO
close(fd00);
}
execvp(sa[0], sa);
perror("execvp");
_exit(1);
printf("Could not execute '%s'\n", sa[0]);
default:// This is the parent
wait(&status);
return (status == 0) ? 0: 1;
}
}
答案 0 :(得分:1)
fork()
。exec()
。在你fork()
之后,在孩子身上完成所有这一切,就像重定向一样。