0

I wrote my own shell in c, and I would like to test it through a script that send multiples inputs one by one to my program.

My program is a loop that never ends and keeps getting user input, depending on the input it will call the right function.

An example of what I would like to simulate :

./myownshell.o ( Program is already compiled >> Start program )
cd folder1  ( Program is waiting for user input >> Send "cd folder 1 " -> Enter )
ls ( Program is waiting for another user input >> Send "ls" -> Enter )

I've tried every solution from : How do I provide input to a C program from bash? but no chance

Simplified code :

#include <stdio.h>
#include <string.h>
#include <unistd.h>
void hello(){

    write(1,"hello",strlen("hello"));
}

void bye(){
    write(1,"bye",strlen("bye"));
}


void shell(){
    int r;
    char cmd[200];
    memset(cmd,'\0',200);
    while((r = read(0, cmd, 200)) == 0);

    if(strncmp(cmd,"hello",strlen("hello")) == 0){
        hello();
    }

    if(strncmp(cmd,"bye",strlen("bye")) == 0){
        bye();
    }
    shell();
}


int main(int argc, char **argv) {
   shell();
}

And in bash :

./test <<'EOF'
hello
bye
EOF
Shewol
  • 1
  • 1
  • Use `fgets()` ... or write your own inplementation of it using `read()` with a size of `1` within a loop. – pmg Dec 30 '20 at 10:02
  • I've edited and put the simpified code of what I'm trying to do and the bash script too. When I run the bash script, it just writes "Hello" but doesn't call the function and when I write it myself nothing happens anymore, with "bye" too even though they work normally when not run from bash – Shewol Dec 30 '20 at 10:03
  • Look into `expect`. – Shawn Dec 30 '20 at 10:09
  • 1
    shells expect lines of input ending in a newline which is what fgets does.. read expects a fixed number of characters. – stark Dec 30 '20 at 12:14

0 Answers0