c - 带有 C 文件输入和输出的 shell

标签 c shell

我在后台运行交互式 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;
}    

最佳答案

你想要这个:

                /* 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;
}    

我写得很快;试一试,告诉我你是否想要

关于c - 带有 C 文件输入和输出的 shell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15932537/

相关文章:

c - 动态内存分配总是留下/访问影子字节

python - 如何使用 "at"unix 命令直接从终端调度 python 脚本?

macos - 每次都获取相同的 shell 脚本文件

c - 加载 shell 脚本的函数而不执行它

c - 如何在 C 语言中为特定的结构类型正确使用 free

SDL 中的跳棋游戏

linux - 为什么我不能执行这个脚本?

linux - 我可以运行使用 2 个不同命令行的脚本吗?

C float 小数不被内存

c - 带二维数组的双指针