“服务器”程序端:
#define RESP_FIFO_NAME "response"
/* Global Variables */
char *cmdfifo = CMD_FIFO_NAME; /* Name of command FIFO. */
char *respfifo = RESP_FIFO_NAME; /* Name of response FIFO. */
int main(int argc, char* argv[]) {
int infd, outfd; /* FIFO file descriptors. */
... // blah blah other code here
/* Create command FIFO. */
if (mkfifo(cmdfifo, FIFO_MODE) == -1) {
if (errno != EEXIST) {
fprintf(stderr, "Server: Couldn’t create %s FIFO.\n", CMD_FIFO_NAME);
exit(1);
}
}
/* Create response FIFO. */
if (mkfifo(respfifo, FIFO_MODE) == -1) {
if (errno != EEXIST) {
fprintf(stderr, "Server: Couldn’t create %s FIFO.\n", RESP_FIFO_NAME);
exit(1);
}
}
/* Open the command FIFO for non-blocking reading. */
if ((infd = open(cmdfifo, O_RDONLY | O_NONBLOCK)) == -1) {
fprintf(stderr, "Server: Failed to open %s FIFO.\n", CMD_FIFO_NAME);
exit(1);
}
/* Open the response FIFO for non-blocking writes. */
if ((outfd = open(respfifo, O_WRONLY | O_NONBLOCK)) == -1) {
fprintf(stderr, "Server: Failed to open %s FIFO.\n", RESP_FIFO_NAME);
perror(RESP_FIFO_NAME);
exit(1);
}
该程序打印以下输出:
Server: Couldn’t create response FIFO.
我对FIFO知之甚少,因为我的教授没有教它。这就是我通过阅读他的例子和讲义所能做到的。我试过没有 O_NONBLOCK 标志,但这只会导致程序挂起,所以它是必需的。我不明白为什么读取 FIFO 很好,但写入 FIFO 无法打开。