我正在编写一个程序,当从两个单独的 bash 会话作为两个单独的进程运行时,会在两者之间打开一个命名管道,以允许将字符串从一个发送到另一个。
当进程第一次从一个终端执行时,它会检查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;
}