3

I need help closing a named pipe. I created a named fifo via mkfifo myfifo, then some C++ executable files wrote/read from myfifo, and now I wish to close it (so I can cat its contents to read them).

However, I read the man mkfifo page, and also googled around, but I cannot find any specific command to close the fifo (even after all executables are done using it).


The commands involved are:

$ mkfifo myfifo
$ ./A < myfifo | ./B > myfifo
$ # now i want to read myfifo

(the executables A and B interact with each other via myfifo)


These are the files

// B.cpp

#include <fstream>
#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
using namespace std;

int main()
{
    ofstream file("inter.txt");
    int in = -1;
    if (file.is_open())
    {
        cin >> in;
        cout << (in + 1);
    }
    else
        cout << -1;
    file << in;
    file.close();
    return 0;
}

// A.cpp

#include <fstream>
#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
using namespace std;
#define PIPE "pipe.txt"
#define MAX_BUF 150

int main()
{
    ofstream file("inter2.txt");
    cout << 1 << endl;
    file << 1;
    int in;
    cin >> in;
    cout << 2 * in;
    file << 2 * in;
    file.close();
    return 0;
}

In the above program, this is supposed to happen: A outputs 1. B reads 1 and outputs 2. A reads 2 and outputs 4. Then the programs end.

  • Stop ./A or ./B. – Cyrus Dec 9 '18 at 13:35
  • @Cyrus but how to do that? – Gaurang Tandon Dec 9 '18 at 13:39
4

It is that once the contents of a FIFO have been consumed, they won't remain in the FIFO. Thus, it is not possible to print all the contents of a FIFO later (only those that weren't consumed would remain).

The only way to know what was being sent to the FIFO is to print the same thing to a separate file (possibly overload the stream insertion operator <<).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.