我正在尝试在C
中开发电梯模拟器应用程序,因此我即将使用共享内存和管道进行内部数据库通信。 为了让我的生活更轻松一点,我宣布了两个函数read_from_pipe
和write_to_pipe
。不能让'孩子'和'父母'一起正确通信
下面是我main
代码的一部分,我需要找出原因预期不会表现:
01 #include <stdio.h>
02 #include <stdlib.h>
03 #include <string.h>
04 #include <sys/types.h>
05 #include <sys/stat.h>
06 #include <fcntl.h>
07 #include <sys/mman.h>
08
09 #include "windows.h"
10
11 #define READ 0
12 #define WRITE 1
13
14 typedef struct lift
15 {
16 int winch_control;
17 int door_control;
18 int call_buttons;
19 int lift_buttons;
20 double position;
21 double door_ajar;
22 int quit;
23 int reset;
24 int error;
25 } lift;
26 int main(void)
27 {
28 lift *pLift;
29 pid_t pid;
30 off_t off = 0;
31 int liftfd, mmlen = sizeof(lift), FIFO[2];;
32
33 pid = fork();
34 liftfd = open("liftfile", (O_CREAT | O_RDWR), 0666);
35 pLift = (lift *)mmap((caddr_t)0, mmlen, (PROT_READ | PROT_WRITE), MAP_SHARED, liftfd, off);
36
37 if (pipe(FIFO)) // create pipe failed
38 {
39 fprintf(stderr, "Pipe failed.\n");
40 return EXIT_FAILURE;
41 }
42
43 if (pid == (pid_t)0) // child process
44 {
45 close(FIFO[WRITE]);
46 read_from_pipe(FIFO[READ]);
47 close(FIFO[READ]);
48 }
49 else if (pid < (pid_t)0) // create fork failed
50 {
51 fprintf(stderr, "Fork failed.\n");
52 return EXIT_FAILURE;
53 }
54 else // parent process
55 {
56 close(FIFO[READ]);
57 write_to_pipe(FIFO[WRITE],"UP3" , 56);
58 close(FIFO[WRITE]);
59 }
60 }
read_from_pipe
子程序:
void read_from_pipe(int fileDescriptr)
{
FILE *stream;
int c;
stream = fdopen(fileDescriptr, "r");
while ((c = fgetc(stream)) != EOF)
putchar(c);
fclose(stream);
}
write_to_pipe
子程序:
void write_to_pipe(int fileDescriptr , char *stateName , int timerValue)
{
FILE *stream;
stream = fdopen(fileDescriptr, "w");
fprintf(stream, "Current system state:\t%s\n", stateName);
fprintf(stream, "Timer value:\t\t%d\n",timerValue);
fflush(stream);
fclose(stream);
}
夫妻俩我窝我想指出:
- 如果有人想要参考特定的 行,我会提供行号。我假设每个人都知道如何在代码 编辑器中使用列模式,并将其全部删除,以便编译成功。
- 代码中的许多内容可能看起来多余,但实际上它们正在代码中的其他地方使用。因此,如果您选择了任何一项,请忽略 冗余。
- 我在Windows上使用CygWin。
根据行号57
,我的预期结果是:
Current system state: UP3
Timer value: 56
不过,我得到一个空白屏幕。
任何想法我做错了什么?
您是对的。我在'pipe()'调用后将所有内容放入'else'语句中,并且工作正常! – Bababarghi