0

私は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);
    }
}
4

2 に答える 2

0

Quoth man dup2

これらのシステムコールの1つから正常に戻った後、古いファイル記述子と新しいファイル記述子を同じ意味で使用できます。それらは同じ開いているファイルの説明を参照します(open(2)を参照)…</ p>

したがって、dup2(エラーリターンをチェックする必要があります)を呼び出した後、閉じます。これは、まったく同じ記述子であるためですoldfdnewfd

私が理解できないのは、なぜgrep --helpまったく機能するのかということですが、その質問に答えるのに十分なコードが表示されていません。

次のコメントを追加しました:あなたはまだ十分なコードを与えていません。何よりも機能していない場合grepは?動作しますかwc /etc/hosts?grepには特別なことは何もありません。実際、grepは完全に特別でないUnixフィルターです。

于 2011-08-15T12:12:22.000 に答える
0

問題は、シェルで引用符を使用することです。Bash は多くのことをバックグラウンドで実行します。grep -i perror shell.c は、bash から実行したときに予想されるものは何でも、シェルに出力を与えるはずです。

于 2011-08-16T13:43:37.513 に答える