我正在尝试用c编写一个shell,除了grep之外它大部分都可以工作。每当我在 shell 中发出 grep 命令时,它就不会输出任何东西。这是我用来创建新子进程然后在其中运行 execvp() 的部分代码。
dup2 中的文件描述符(fd_in 和 fd_out)作为参数传递给具有此代码的函数。最有趣的是,当我输入 'grep' 或 'grep --help' 时,它会像往常一样显示。我错过了什么吗?或者必须用 grep 做一些特别的事情?
这就是我的 shell 发生的情况:从 bash 运行时的最后一个命令输出。
--> grep
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.
--> wc /etc/hosts
11 33 314 /etc/hosts
--> grep -i "perror" shell.c
-->
这是代码:
void
create_process(char *cmd_argv[], int fd_in, int fd_out, char *buffer_copy) {
/*Flag bit for Background processes*/
int FLAG = 0;
pid_t cpid;
int status;
int i = 0,j = 0;
/*Find the no. of arguments*/
while(cmd_argv[j] != NULL)
j++;
/*Set the flag bit*/
if(strcmp("&", cmd_argv[j-1]) == 0) {
FLAG = 1;
cmd_argv[j-1] = NULL;
}
//Create a child process
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
//In the child...
if (cpid == 0) {
/*Checking if the file descriptors are already assigned*/
/*For stdin*/
if (fd_in != STDIN_FILENO) {
dup2(fd_in, STDIN_FILENO);
close(fd_in);
}
/*For stdout*/
if (fd_out != STDOUT_FILENO) {
dup2(fd_out, STDOUT_FILENO);
close(fd_out);
}
/*Run the cmd specified*/
status = execvp(cmd_argv[0], cmd_argv);
/*In case of errors*/
if(status < 0) {
perror("execvp ");
exit(1);
}
}
//In the parent...
else {
if(FLAG == 1) {
/*Find where the new bg process can be inserted*/
while(1) {
if (bgprocess[i].pid == 0) {
bgprocess[i].pid = cpid;
strcpy(bgprocess[i].cmd, buffer_copy);
break;
}
i++;
}
printf("[%d] : %s\n", cpid, cmd_argv[0] );
}
/*If not bg, wait for the process to exit*/
else
waitpid(cpid, NULL, 0);
}
}