gpt4 book ai didi

c - 为什么 stat() 返回 EFAULT?

转载 作者:太空宇宙 更新时间:2023-11-04 02:05:09 24 4
gpt4 key购买 nike

我正在编写一个程序,当从两个单独的 bash session 作为两个单独的进程运行时,打开两者之间的命名管道以允许字符串从一个发送到另一个。

当进程第一次从一个终端执行时,它会检查 stat(fname, buf) == -1查看路径中的文件是否为 fname存在,如果不存在,则创建它。然后该过程假定,因为它是制作 FIFO 的人。 ,它将通过它发送消息并相应地继续。

在那之后,程序可以从另一个终端运行,该终端应该通过检查 stat(fname, buf) == -1 来确定它将成为通过管道的消息的接收者。 .现在条件应该返回 false,并且 stat(fname, buf)本身应该返回 0因为在 fname 处存在一个文件现在。

但是由于我无法辨别的原因,当第二个进程运行时,stat(fname, buf)仍然返回 -1 .变量 errno设置为 EFAULT . man stat() 的页面只描述EFAULT作为“错误地址”。任何帮助确定错误发生原因或“错误地址”的含义的帮助。将不胜感激。

我已验证该文件确实是由第一个进程按预期创建的。第一个进程在 pipe = open(fname, O_WRONLY); 行等待因为它不能继续到 pipe 的另一端已打开。

编辑:以下是我的代码的独立实现。我已确认它可以编译并遇到我在此处描述的问题。

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#define MAX_LINE 80
#define oops(m,x) { perror(m); exit(x); }

int main(int argc, char const *argv[]) {
char line[MAX_LINE];
int pipe, pitcher, catcher, initPitcher, quit;
struct stat* buf;

char* fname = "/tmp/absFIFOO";
initPitcher = catcher = pitcher = quit = 0;

while (!quit) {
if (((!pitcher && !catcher && stat(fname, buf) == -1) || pitcher) && !quit) {
// Then file does not exist
if (errno == ENOENT) {
// printf("We're in the file does not exist part\n");
if (!pitcher && !catcher) {
// Then this must be the first time we're running the program. This process will take care of the unlink().
initPitcher = 1;
int stat;
if (stat = mkfifo(fname, 0600) < 0)
oops("Cannot make FIFO", stat);
}
pitcher = 1;

// open a named pipe
pipe = open(fname, O_WRONLY);

printf("Enter line: ");
fgets(line, MAX_LINE, stdin);

if (!strcmp(line, "quit\n")) {
quit = 1;
}

// actually write out the data and close the pipe
write(pipe, line, strlen(line));
close(pipe);
}
} else if (((!pitcher && !catcher) || catcher) && !quit) {
// The first condition is just a check to see if this is the first time we've run the program. We could check if stat(...) == 0, but that would be unnecessary
catcher = 1;

pipe = open("/tmp/absFIFO", O_RDONLY);

// set the mode to blocking (note '~')
int flags;
flags &= ~O_NONBLOCK;
fcntl(pipe, F_SETFL, flags); //what does this do?

// read the data from the pipe
read(pipe, line, MAX_LINE);

if (!strcmp(line, "quit\n")) {
quit = 1;
}

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

// close the pipe
close(pipe);
}
}
if (initPitcher)
unlink(fname);

return 0;
}

最佳答案

你有这段代码:

struct stat* buf;
...
if (((!pitcher && !catcher && stat(fname, buf) == -1)

当您调用 stat() 时,buf 没有初始化,也不知道它指向什么。

您必须为其分配一些存储空间,以便 stat() 有一个有效的位置来存储结果。最简单的事情就是在堆栈上分配它:

struct stat buf;
...
if (((!pitcher && !catcher && stat(fname, &buf) == -1)

关于c - 为什么 stat() 返回 EFAULT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21622429/

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