how to turn program into deamon program

132 views Asked by At

I sometimes write program like this to process offline data:

load_model() //this may cost lots of time
while(cin >> inputs)
{
    result = process_input(inputs)
    cout << result
}
release_model()

This works fine if I only have to process offline data. However, when the data comes one by one I am in trouble. Since I have to load the model everytime which is time consuming.

I wonder if there is any way to CONVERT this program into a service WITHOUT modify the program itself. For example, I can redirect the cin and cout to two named pipes:

program < namedpipe_in > namedpipe_out

The I can put the inputs into the namedpipe_in like this

cat input > namedpipe_in

and read the result in another pipe:

cat namedpipe_out

However, this solution will not work since once I cat something to the namedpipe_in, the pipe will be close after cat operation and the program exits.

My question is how to fix this problem and make the pipes looks more like a queue instead of a memory buffer.

Thanks for your time reading.

1

There are 1 answers

0
kotakotakota On

Perhaps I am misunderstanding your question; please correct me if this is not what you are looking for.

To simulate your example, I wrote a simple C++ program which just takes in each input string and reverses it:

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::cout << ":start:" << std::endl;
    std::string str;
    while(std::cin >> str)
    {
        std::reverse(str.begin(), str.end());
        std::cout << str << std::endl;
    }
}

The output binary of my example program is strflipper.

I have another file called in.log which is just an input file which I created via touch in.log.

Now I call

tail -f in.log | ./strflipper > out.log

and if I add something to the input log in a different terminal, the output log gets adjusted as such:

$ echo "abc" >> in.log
$ echo "foo" >> in.log
$ echo "bar baz" >> in.log

$ cat out.log
:start:
cba
oof
rab
zab

which of course is my expected output. As long as I don't kill the program, anything I add into in.log will automatically be processed within that loop without killing or restarting strflipper.