私はcでシェルを書き込もうとしていますが、grepを除いてほとんど機能します。シェルでgrepコマンドを実行すると、何も出力されません。これは、新しい子プロセスを作成し、その中でexecvp()を実行するために使用するコードの一部です。
dup2のファイル記述子(fd_inおよびfd_out)は、このコードを持つ関数に引数として渡されます。そして最も興味深いことに、「grep」または「grep --help」を指定すると、通常どおり表示されます。私は何かが足りないのですか?または、grepで何か特別なことをする必要がありますか?
これが私のシェルで起こることです:最後のコマンドは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);
}
}