2013-04-10 56 views
1

我有一些麻煩,在輸入和輸出重定向到文件中的背景中運行交互式shell(/ bin/bash,/ bin/sh for ins)。我嘗試了不同的東西,但它不起作用。外殼與輸入和輸出文件在C

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 

int main(void) { 

    char *argve[2]; 
    argve[0]="/bin/sh"; 
    argve[1]=NULL; 

    FILE *fichin, *fichout; 
    fichin=fopen("/root/C/fichin.temp", "w+"); 
    fichout=fopen("/root/C/fichout.temp", "w+"); 

    dup2(fileno(fichin), 0); //stdin 
    dup2(fileno(fichout), 1); //stdout 
    dup2(fileno(fichout), 2); //stderr 

    /*freopen("/root/C/fichin.temp", "r", stdin); 
    freopen("/root/C/fichout.temp", "w+", stdout);*/ 

    system("/bin/sh"); 
    //execve("/bin/sh", argve, NULL); 

    return 0; 
}  
+0

你的問題到底是什麼? – squiguy 2013-04-10 17:29:40

+1

你確定應該用'w +'模式打開'fichin.temp'嗎?它看起來應該是'r',因爲它是輸入文件。 – Ale 2013-04-10 17:30:46

+0

爲什麼這段代碼不工作?我如何在後臺輸入和輸出重定向到文件中運行交互式shell(/ bin/bash,/ bin/sh)? – joub 2013-04-10 17:31:15

回答

0

你想這樣的:

   /* shell interactive */ 


#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h> 

int main(int argc, char **argv) { 

    int file_input ; 
    int file_output; 
    int size_read = 0; 
    pid_t pid_command; 

    char _command[10]; 
    char *read_one_char=NULL; 
    char command_separator; 
    int i=0; 
       /* open file input on READONLY */ 

       /* open return file descriptor */ 
    file_input = open("fichin.temp", O_RDONLY , 0666); 

    if (file_input <0) 
     { 
    perror("can't open input file"); 
     } 

    file_output = open("fichout.temp", O_CREAT | O_TRUNC | O_WRONLY , 0666) ; 

    if (file_output < 0) 
     { 
    perror("can't open output file"); 
     } 

    read_one_char = malloc(sizeof(char)); 
    if (read_one_char == NULL) 
     { 
    perror(" malloc failed "); 
     } 

    dup2(file_input, 0); //stdin 
    dup2(file_output, 1); //stdout 
    dup2(file_output, 2); //stderr 



    /*reading commands assuming that each line is a command 
     command 1 
     command 2 
     .. 
     command n 

     you can change command_seperator 
    */ 

    command_separator = '\n'; 

    do 
     { 

    size_read = read(file_input,(void*)read_one_char,1); 

    if (*read_one_char!=command_separator && size_read > 0) 
     { 
     _command[i]=*read_one_char; 
     i++; 
     } 
    else 
     { 
     _command[i--]='\0'; 
     i=0; 

     write(1,"\n\t============ output for command ==========\n",45); 
     system(_command); 

     } 
     }while(size_read != 0); 




    return 0; 
}  

我很快寫的;試試吧,告訴我它是否需要