- 论坛徽章:
- 0
|
这个例子的代码一共有三个文件,client.c, server.c以及mainfifo.c。
先上代码:
client.c
1 #include <unistd.h>
2 #include <stdio.h>
3 #include <string.h>
4
5 #define MAXLINE 4096
6
7 void
8 client(int readfd, int writefd)
9 {
10 size_t len;
11 ssize_t n;
12 char buff[MAXLINE];
13
14 /* 4read pathname */
15 fgets(buff, MAXLINE, stdin);
16 len = strlen(buff); /* fgets() guarantees null byte at end */
17 if (buff[len-1] == '\n')
18 len--; /* delete newline from fgets() */
19
20 /* 4write pathname to IPC channel */
21 write(writefd, buff, len);
22
23 /* 4read from IPC, write to standard output */
24 while ( (n = read(readfd, buff, MAXLINE)) > 0)
25 write(STDOUT_FILENO, buff, n);
26 }
server.c代码:
1 #include <unistd.h>
2 #include <fcntl.h>
3 #include <errno.h>
4 #include <string.h>
5 #include <stdio.h>
6
7 #define MAXLINE 4096
8 void
9 server(int readfd, int writefd)
10 {
11 int fd;
12 ssize_t n;
13 char buff[MAXLINE+1];
14
15 /* 4read pathname from IPC channel */
16 if ( (n = read(readfd, buff, MAXLINE)) == 0)
17 {
18 perror("end-of-file while reading pathname");
19 exit(0);
20 }
21 buff[n] = '\0'; /* null terminate pathname */
22
23 if ( (fd = open(buff, O_RDONLY)) < 0) {
24 /* 4error: must tell client */
25 snprintf(buff + n, sizeof(buff) - n, ": can't open, %s\n",
26 strerror(errno));
27 n = strlen(buff);
28 write(writefd, buff, n);
29
30 } else {
31 /* 4open succeeded: copy file to IPC channel */
32 while ( (n = read(fd, buff, MAXLINE)) > 0)
33 write(writefd, buff, n);
34 close(fd);
35 }
36 }
mainfifo.c 代码
1 #include <fcntl.h>
2 #include <errno.h>
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 #include <stdio.h>
6
7 #define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
8 #define fifo1 "/tmp/fifo1"
9 #define fifo2 "/tmp/fifo2"
10
11 void client(int, int), server(int, int);
12
13 int main(int argc, char **argv)
14 {
15 pid_t childpid;
16
17 int readfd, writefd;
18
19 if ((mkfifo(fifo1, FILE_MODE) < 0) && (errno != EEXIST))
20 {
21 printf("mkfifo");
22 exit(0);
23 }
24 if ((mkfifo(fifo2, FILE_MODE) < 0) && (errno != EEXIST))
25 {
26 unlink(fifo1);
27 printf("mkfifo");
28 exit(0);
29 }
30
31 if ((childpid = fork()) == 0)
32 {
33 readfd = open(fifo1, O_RDONLY, 0);
34 writefd = open(fifo2, O_WRONLY, 0);
35 server(readfd, writefd);
36 exit(0);
37 }
38
39 writefd = open(fifo1, O_WRONLY, 0);
40 readfd = open(fifo2, O_RDONLY, 0);
41
42 client(readfd, writefd);
43 waitpid(childpid, NULL, 0);
44
45 close(readfd);
46 close(writefd);
47 unlink(fifo1);
48 unlink(fifo2);
49
50 exit(0);
51 }
程序的意图是演示fifo在父子进程间的使用,父进程读取stdin输入作为一个文件名,然后通过管道传给子进程,子进程打开该文件,读取文件内容然后把内容
通过管道传给父进程,父进程然后将内容输出到stdout。
上边的程序没有问题,我的问题是在mainfifo.c中,如果把39和40行调换顺序,那么程序不正常,为什么?
结贴:已经在书上看到原因了
[ 本帖最后由 puccoon 于 2008-6-3 18:24 编辑 ] |
|