How to turn a program into a deamon program

I sometimes write a program like this to handle offline data:

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

      

This works great if I have to handle offline data. However, when the data comes in one by one, I have problems. As I have to load the model every time it takes a long time.

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

program < namedpipe_in > namedpipe_out

      

I can insert input into namedpipe_in like this

cat input > namedpipe_in

      

and read the result in another channel:

cat namedpipe_out

      

However, this solution won't work as long as I ever generate something in namedpipe_in, the pipe will be closed after cat operation and the program will exit.

My question is how to fix this problem and make the pipes look more like a queue rather than a memory buffer.

Thanks for reading the time.

+3


source to share


1 answer


I may not understand your question; please correct me if this is not what you are looking for.

To simulate your example, I wrote a simple C ++ program that just takes in each line of input and changes 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 named in.log

, which is just the input file that I created via touch in.log

.



Now I am calling

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

      

and if I add something to the input log in another terminal, the output log is configured 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. Until I kill the program, anything I add to in.log

will be automatically processed in this loop without killing or restarting strflipper

.

+1


source







All Articles