I have a simple Linux C program that I’m writing to help me better understand IPC, right now I’m trying to build it with pipes.
I have a single code base that I run in two different terminal windows as two different executables (so they can talk to each other). However I’m not doing something correct, because I never get any data to read, but I’m not sure what…
NOTE This is not the full code, I chopped out the output/input/validation to save space. But it’s noted in the comments in the program below.
void main()
{
int pipefd[2], n;
char input = 0;
char buffer[100] = {0};
char outpipe[100] = {0};
if(pipe(pipefd) < 0) {
printf("FAILED TO MAKE PIPES\n");
return;
}
printf("Starting up, read fd = %d, write fd = %d\n", pipefd[0],pipefd[1]);
do {
//print menu options (send message, get message, get my fd,
// set a fd to talk to, quit)
// if "send a message":
{
printf("What would you like to send?\n");
fgets(buffer, 100, stdin);
write(pipefd[1], buffer, strlen(buffer));
}
//else if "read a message":
{
if(open(outpipe, 0) < 0)
printf("Couldn't open the pipe!\n");
else {
n = read(outpipe, buffer, 100);
printf("I got a read of %d bytes\nIt was %s\n",n, buffer);
close(outpipe);
}
}
//else if "get my file descriptor":
printf("My fd tag is: /proc/%d/fd/%d\n", (int)getpid(), pipefd[0]);
//else if "set a file descriptor to talk to":
{
printf("What is the pipe's file descriptor?\n");
fgets(outpipe, 100, stdin);
n = strlen(outpipe) - 1;
outpipe[n] = '\0';
}
} while (input != 'Q');
return;
}
I know the pipes are created successfully, I verified the file descriptors are in place:
lr-x------ 1 mike users 64 Sep 26 23:31 3 -> pipe:[33443]
l-wx------ 1 mike users 64 Sep 26 23:31 4 -> pipe:[33443]
Looks like the permissions are OK (read on pipe 3, write on pipe 4).
I use it as such:
//terminal 1
Pick an option:
3
My fd tag is: /proc/8956/fd/3
//terminal 2
Pick an option:
4
What is the pipe's file descriptor?
/proc/8956/fd/3
Pick an option:
1
What would you like to send?
hello
//terminal 1
Pick an option:
2
I got a read of -1 bytes
It was
Is there anything obviously wrong that I’m doing here? My reads always get “-1” return value…
It seems you have misunderstood how pipe works. A pipe is an anonymous file descriptor that is not going by file in the file system. The files in
/proc/<pid>/fdyou don’t have to care about.Here is a rewrite of what you are trying to do: