3

私は単純なシェルに取り組んでいますが、今はリダイレクトを理解しようとしています。ls コマンドをハードコーディングして、今のところファイルに書き込もうとしています。現在、ls が実行され、出力ファイルが作成されますが、出力は引き続き stdout に送られ、ファイルは空白です。なぜだか混乱しています。前もって感謝します。

これが私のコードです:

int main()
{
    int ls_pid; /* The new process id for ls*/
    char *const ls_params[] = {"/bin/ls", NULL}; /* for ls */
    int file; /* file for writing */

    /* Open file check user permissions */
    if (file = open("outfile", O_WRONLY|O_CREAT) == -1) /* , S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP */
    {
        perror("Failed to open file");
        _exit(EXIT_FAILURE);
    } 

    ls_pid = fork(); /* Create new process for ls */

    if (ls_pid == -1) /* error check */
    {
        perror("Error forking ls (pid == -1)");
        _exit(EXIT_FAILURE);
    }
    else if (ls_pid == 0) /* Child of ls */
    {
        /* Redirect output to file */
        if (dup2(file, STDOUT_FILENO) == -1) /* STDOUT_FILENO = 1 */
        {
            perror("Error duping to file");
            _exit(EXIT_FAILURE);
        }
        close(file);

        execvp("ls", ls_params); /* create the sort process */
        /* execlp("ls", "ls", NULL); */

        /* if this does not end the program, something is wrong */
        perror("Exec failed at sort");
        _exit(EXIT_FAILURE);
    }
    else /* ls parent (1) */
    {
        /* wait for child */
        if (wait(NULL) == -1)
        {
            perror("fork failed on parent");
            _exit(EXIT_FAILURE);
        }
    }

}
4

1 に答える 1

0

問題はありません。私はあなたのコードを自分で試しました。そしてそれはうまくいきます!私の簡略化されたコードは次のようになります。

int main(void) {
    int fd;

    char* const param[] = {"/bin/ls", NULL};

    fd = open("outfile", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);

    if (fd < 0) {
        perror("open failed\n");
        exit(0);
    }

    pid_t pid = fork();

    if (pid < 0) {
        perror("fork failed\n");
        exit(0);
    }
    else if (pid == 0) {
        dup2(fd, STDOUT_FILENO);

        close(fd);

        execvp("ls", param);
    }
    else {
        wait(NULL);
    }
}

コンパイルして実行し、出力ファイルで期待される結果を見つけます。

唯一の違いは、S_IRUSER | でフィード オープンすることです。S_IWUSER アクセス許可オプションを使用しないと、開くことができません。あなたのコードにも同様のことが見られますが、どういうわけかあなたはそれらにコメントしました...

于 2012-03-10T13:41:09.903 に答える