我正在尝试重定向输出,但我有 2 个问题。问题 1: ls -l > file 工作正常,但如果我执行 cat file1 > file2,我的 shell 似乎在后台无限期地工作。我必须在等待 2 到 3 分钟后中断它(Ctrl-D)。问题 2:使用 sort < fruits 时同样的问题,我的 shell 似乎在等待一个进程完成,但它永远不会。所以我不得不打断它。我知道我做的不对,但我似乎无法弄清楚什么是错的/缺少的。我还没有实现管道。您的帮助将不胜感激。
int create_childprocess(char *argv[], int argc)
{
//int pid;
int fd, i, ret;
pid_t pid;
int redirect_sign =0;
if((pid = fork()) == -1)
{
/*error exit -fork failed*/
perror("Fork failed");
exit(-1);
}
if(pid == 0)
{
/*this is the child*/
printf("\nThis is the child ready to execute: %s\n", argv[0]);
for(i=0; i<argc; i++)
{
if((strcmp(">", argv[i])) ==0)
redirect_sign=1;
else if((strcmp(">>", argv[i])) ==0)
redirect_sign=2;
else if((strcmp("<", argv[i])) ==0)
redirect_sign=3;
else if((strcmp("<<", argv[i])) ==0)
redirect_sign=4;
}
if (redirect_sign==1) //if ">" is found...
{
fd = open(argv[argc-1],O_TRUNC | O_WRONLY | O_CREAT, 0755);
if(fd == -1)
{
/*An error occured. Print an error message and bail.*/
perror("open");
exit(-1);
}
else
{
printf("Writing output of the command %s to file created\n", argv[0]);
dup2(fd,1);
execlp(argv[0], argv[0], NULL);
close(fd);
}
}
else if (redirect_sign==2) //if ">>" was found...
{
fd = open(argv[argc-1], O_WRONLY | O_APPEND | O_CREAT, 0755);
if(fd == -1)
{
/*An error occured. Print an error message and bail.*/
perror("open");
exit(-1);
}
else
{
printf("Appending output of the command %s to file created\n", argv[0]);
dup2(fd,1);
execlp(argv[0], argv[0], NULL);
close(fd);
}
}
else if (redirect_sign==3) //if "<" was found...
{
fd = open(argv[argc-1], O_TRUNC | O_WRONLY | O_CREAT, 0755);
if(fd == -1)
{
/*An error occured. Print an error message and bail.*/
perror("open");
exit(-1);
}
else
{
printf("Writing content of file %s to disk\n", argv[argc-1]);
dup2(fd,1);
execlp(argv[0], argv[0], NULL);
close(fd);
}
}
else if (redirect_sign==4) //if "<" was found...
{
fd = open(argv[argc-1], O_TRUNC | O_WRONLY | O_CREAT, 0755);
if(fd == -1)
{
/*An error occured. Print an error message and bail.*/
perror("open");
exit(-1);
}
else
{
printf("Writing content of file %s to %s \n", argv[argc-1], argv[0] );
dup2(fd,1);
execlp(argv[0], argv[0], NULL);
close(fd);
}
}
else //if ">" or ">>" or "<" or "<<" was not found
{
execvp(argv[0], &argv[0]);
/*error exit - exec returned*/
perror("Exec returned");
exit(-1);
}
}
else
{
/*this is the parent -- wait for child to terminate*/
wait(pid,0,0);
printf("\nThe parent is exiting now\n");
}
free (argv);
return 0;
}