I'm having some trouble to run an interactive shell (/bin/bash, /bin/sh for ins) in the background with input and output redirected in files. I tried different things but it does not work.
#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;
}
you want this :
/* 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;
}
i wrote it quickly; try it and tell me if its that you want
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.