Reputation: 99
I apologize for the bad title as I wasn't exactly sure how to word it. I have to make a named pipe in C++ for an assignment. I understand how the named pipe works and what each line should do, but I'm running into a problem that me and a friend who's code is IDENTICAL can't solve.
It is a simple assignment. All I have to do is have one program create the named pipe and put a user inputted char array into it. The second program (in its own terminal) just reads the char array from the pipe and outputs it in the terminal.
In the second program below at line 11 (c = open("/tmp/myfifo", O_RDONLY);), the program never seems to run that line. When I run it in the terminal, nothing happens and it just sits there as if it's in deadlock. My friend does not have this problem and we have no idea what could be causing it. I am running on Ubuntu 14.04.3 in a Virtual Box using the default terminal.
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
#include <string>
using namespace std;
int main() {
int a, b, c, res;
string input;
char buffer [50];
b = access("/tmp/myfifo", F_OK);
if (b == -1)
a = mkfifo("/tmp/myfifo", 0777);
c = ("/tmp/myfifo", O_WRONLY);
getline(cin, input);
for (int i = 0; i < input.size(); i++)
buffer[i] = input.at(i);
res = write(c, buffer, 50);
close(c);
return 0;
}
.
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
using namespace std;
int main() {
int c, res;
char buffer [50];
c = open("/tmp/myfifo", O_RDONLY);
res = read(c, buffer, 50);
close(c);
cout<<buffer;
return 0;
}
Upvotes: 0
Views: 599
Reputation: 75575
It appears that you missing the word open
on line 16 in the sender.
c = open("/tmp/myfifo", O_WRONLY);
Without that word, your program invokes the comma operator, which will assign to c
the value of O_WRONLY
, as described here.
One other independent bug I noticed while running this is that you did not initialize buffer
on the sender side, which means the receiver may read garbage after the actual string because there's no null terminator.
char buffer [50];
memset(buffer, 0, 50);
Upvotes: 3