【发布时间】:2012-09-28 13:41:17
【问题描述】:
我正在编写一个简单的 Linux C 程序,以帮助我更好地理解 IPC,现在我正在尝试使用管道构建它。
我有一个在两个不同终端中运行的单一代码库windows 作为两个不同的可执行文件(因此它们可以相互通信)。但是我没有做正确的事情,因为我从来没有读取任何数据,但我不确定是什么......
注意这不是完整的代码,我删掉了输出/输入/验证以节省空间。但在下面程序的 cmets 中注明了。
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;
}
我知道管道已成功创建,我已验证文件描述符已到位:
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]
看起来权限正常(在管道 3 上读取,在管道 4 上写入)。
我就是这样使用它的:
//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
我在这里做的有什么明显的错误吗?我的读取总是得到“-1”返回值...
【问题讨论】:
-
如果您还没有,请查看 Beej 的指南:beej.us/guide/bgipc
-
我很惊讶你的程序竟然可以编译,因为像对文件的
read和close这样的调用是错误的。 -
@JoachimPileborg - 是的,编译得很好,也没有警告。我想它对于 gcc 来说已经足够接近了。调用不正确怎么办?
-
@Mat - 我打印了它,它是正确的。
strlen()-1设置为 '\0' 是为了摆脱 fgets 附加的'\n' -
其他几件事,你永远不会改变
input,所以它会永远循环;而且你永远不会说 在哪里 你得到了-1返回值;最后,如果出现错误,您不会打印错误。使用例如perror打印可读消息。
标签: c linux ipc pipe communication