0

我浏览了整个互联网和 die.net,但看不到让我的代码工作。我的问题是我能够将输出重定向到文件,但无法将其恢复为标准输出,我尝试使用dup,dup2close,但也许我使用错误。任何帮助将不胜感激,谢谢

. if(myargc >= 3)当我尝试重定向输出时,我的问题从块开始。

main()
{
    int i, myargc =0, background, newfile, file, stdout2, read  = 0, write = 0;
    pid_t pid;
    char input[512], *myargv[60];


while(1)
{
    background = 1;
    printf("Myshell>");
    gets(input);
    //scanf("%s", input);
    myargc = parser(input, myargv);

    if(strcmp(*myargv, "exit") == 0)
    {
        exit(0);
    }

    if(strcmp(myargv[myargc-1], "&") == 0)
    {
        background = 0;
        myargv[myargc-1] = '\0';
        myargc--;
    }

    if(myargc >= 3)
    {
        if(strcmp(myargv[myargc-2], ">") == 0)
        {
            write = 1;
            file = creat(myargv[myargc-1], S_IWUSR);
            myargv[myargc-2] = '\0';

            if(file < 0)
            {
                printf("File could not be created.\n");
            }
            printf("Redirecting output to file %s.\n", myargv[myargc-1]);
            fflush(stdout);
            stdout2 = dup(STDOUT_FILENO);
            //fclose(stdout);  // fclose() for type FILE*
            newfile = dup2(file, 1);  // uses lowest number descriptor (1, since just                         
                                      // closed stdout)
            close(file); // closes old file descriptor duplicate, close() uses int
            myargc = myargc-2;
        }
    }
    if ((pid = fork()) == -1 )
    {
        // if fork fails, print error and exit
        perror("Fork failed");
        exit(-1);
    }
    else if (pid == 0) { // child process

        if (read == 0 && write == 0)
        {
            printf("This is the child ready to execute: ");
            fflush(stdout);
            for (i =0; i < myargc; i++)
            {
                printf("%s ", myargv[i]);
                fflush(stdout);
            }
            printf("\n");
        }
        if (execvp(*myargv,myargv) < 0);
        {
            printf("Execution failed.");
        }/* error exit - exec returned */
        close(newfile);
        dup2(stdout2, STDIN_FILENO);

        //close(file);
        //if (close(file) == 0)
       //{
            //dup2(newfile, STDOUT_FILENO);
            //close(newfile);
            //close(stdout2);
        //    printf("Reopened stdout\n");
       // }
        perror("Exec returned");
        exit(-1);
    }
    close(newfile);
    if (background == 1) { /* this is the parent -- wait for child to terminate */
        wait(pid,0,0);
        printf("The parent is exiting now\n");
    }else{
        waitpid(pid, NULL, WNOHANG); //returns immediately, no wait
    }

    //test for correct parsing
    printf("myargv:\n");
    for (i = 0; i < myargc; i++)
    {
        printf("%s\n", myargv[i]);
    }
    printf("myargc: %d\n", myargc);



    // clear out buffers
    memset(&myargv[0], 0, sizeof(myargv));
    memset(&input[0], 0, sizeof(input));
    }

 }
4

0 回答 0