我在后台运行交互式shell(/ bin / bash,/ bin / sh for ins)时遇到了一些麻烦,输入和输出重定向在文件中。我尝试了不同的东西,但它不起作用。
#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 :(得分: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;
}
我迅速写了;试试看,告诉我你是否想要