casynchronousprocessipc

How to run a continuous bash program and have C start it, get input, and send it output, then gets it's input and then send it output


I've searched around and couldn't quite find and answer to this.

I'm trying to get C to open a bash program called L.

The I want to be able to run the program using something close to system or popen.

Except I want to have the same program running in the back ground and able to make calls to the same program so that it doesn't lose it's memory or history.

Something like this:

// Open program

// Send Hello Program to program

// Get Hello Programer from program

// Send What did I send you to program

// Get Hello Program from program

Solution

  • Here is how to open a bash program in the background and communicate with it from a C program:

    C

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    
    int main() {
        FILE *fp;
        char path[1035];
    
        // Open the process "L" for reading and writing
        fp = popen("./L", "r+");
        if (fp == NULL) {
            printf("Failed to run command\n");
            exit(1);
        }
    
        // Send "Hello Program" to the program
        fprintf(fp, "Hello Program\n");
        fflush(fp);
    
        // Read the response from the program
        fgets(path, sizeof(path), fp);
        printf("Get %s", path);
    
        // Send "What did I send you" to the program
        fprintf(fp, "What did I send you?\n");
        fflush(fp);
    
        // Read the response from the program
        fgets(path, sizeof(path), fp);
        printf("Get %s", path);
    
        // Close the process
        pclose(fp);
        return 0;
    }
    

    Code

    #!/bin/bash
    
    memory=""
    
    while true
    do
        read input
        if [[ "$input" == "What did I send you?" ]]
        then
            echo "$memory"
        else
            memory="$input"
            echo "$input"er
        fi
    done
    

    To compile the C code:

    Code

    gcc -o main main.c
    

    To run the C code:

    Code

    ./main