2 つの別個の bash セッションから 2 つの別個のプロセスとして実行すると、2 つの間の名前付きパイプを開いて、文字列を一方から他方に送信できるようにするプログラムを作成しています。
プロセスが 1 つの端末から最初に実行されるとstat(fname, buf) == -1
、パスにファイルが存在するかどうかが確認され、fname
存在しない場合は作成されます。FIFO
プロセスは、それが を作成するものであったため、それを介してメッセージを送信するものであると想定し、それに応じて続行します。
その後、別の端末からプログラムを実行できます。別の端末は、 をチェックすることによって、パイプを介してメッセージの受信者になることを決定する必要がありますstat(fname, buf) == -1
。現在、条件は false を返す必要があり、現在ファイルが存在するため、stat(fname, buf)
それ自体が返されるはずです。0
fname
しかし、私が識別できない理由により、2 番目のプロセスが実行されると、stat(fname, buf)
まだ が返されます-1
。変数errno
は に設定されEFAULT
ます。のみのman
ページは「Bad address」と記載されています。エラーが発生する理由、または「不正なアドレス」の意味を特定するのに役立ちます。よろしくお願いします。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;
}