gpt4 book ai didi

c - 简单的Linux管道程序,收不到数据

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:58:22 25 4
gpt4 key购买 nike

我有一个简单的 Linux C 程序,我正在编写它来帮助我更好地理解 IPC,现在我正在尝试用管道构建它。
我有一个代码库,我在两个不同的环境中运行终端窗口作为两个不同的可执行文件(因此它们可以相互交谈)。但是我没有做正确的事情,因为我从来没有得到任何数据来读取,但我不确定是什么......

注意 这不是完整的代码,我切掉了输出/输入/验证以节省空间。但在下面程序的评论中已注明。

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”返回值...

最佳答案

看来你误解了管道的工作原理。管道是一个匿名文件描述符,它不按文件系统中的文件进行。 /proc/<pid>/fd 中的文件你不必关心。

这里是你正在尝试做的重写:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(void)
{
int pipefds[2];
char input[128];
char output[128];
ssize_t nread;

if (pipe(pipefds) == -1)
{
perror("Could not create pipe");
return EXIT_FAILURE;
}

printf("Enter input: ");
if (fgets(input, sizeof(input), stdin) == NULL)
{
perror("Could not read input");
return EXIT_FAILURE;
}

/* "Remove" newline from input */
if (input[strlen(input) - 1] == '\n')
input[strlen(input) - 1] = '\0';

/* Now write the received input to the pipe */
if (write(pipefds[1], input, strlen(input) + 1) == -1)
{
perror("Could not write to pipe");
return EXIT_FAILURE;
}

/* Now read from the pipe */
if ((nread = read(pipefds[0], output, sizeof(output))) == -1)
{
perror("Could not reaf from pipe");
return EXIT_FAILURE;
}

/* We don't need to terminate as we send with the '\0' */

printf("Received: \"%s\"\n", output);

return EXIT_SUCCESS;
}

关于c - 简单的Linux管道程序,收不到数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12641175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com