简体   繁体   中英

Custom shell stops working after dup2

I am writing a function to my shell where I need to redirect output to file. For example user write: ls -l >> file and ls -l should be written to file. Almost all things are correct but after first calling my function program stop and I can't write anything else. Below I present my function and I would appreciate any clues to resolve the problem:

void execute2(char *command, char **argv, char **argv2)
{
    pid_t pid;
    int status;

    if ((pid = fork()) < 0) 
    {     
        printf("*** ERROR ***\n");
            exit(1);
    }
    else if (pid == 0) 
    {      
        close(1);    
        parse(command, argv, argv2);
        int output = open(*argv2, O_APPEND | O_WRONLY);
        dup2(output,1);      
        if (strcmp(argv[0], "exit") == 0) 
            exit(0);       
        if (execvp(*argv, argv) < 0) 
        {    
            printf("*** ERROR ***\n");
            exit(1);
        }
        close(output); 
    }
    else 
    {                                  
        while (wait(&status) != pid);
    }
} 

command is command getting from user, argv is part of instruction and parameters and argv2 is the output file.

@Jonathan Leffler I checked this and I think it doesn 't resolve problem. I suggest that when I call first time execute2 it works as well as I want but I never finish that proces. Or I don 't undestand something

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM