【发布时间】:2016-09-12 22:16:27
【问题描述】:
我已经实现了一个 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;
}
}
【问题讨论】:
-
在 SO 和其他网站上有很多关于这个确切问题的问题。你做过搜索吗?如果您真的需要帮助,那么您需要问一个比“我不确定如何正确地 fork() 和 exec()”更具体的问题。答案是您先拨打
fork,然后拨打exec。具体有什么不明白怎么办? -
是的,我进行了很多搜索。我不明白何时何地,以及 STDOUT 和 STDIN 如何与管道一起工作。