管道是一种只允许用在有亲属关系的进程间通信的方式,由函数pipe创建一个管道,read,write进行读写操作。

       #include <unistd.h>

       int pipe(int pipefd[2]);

 参数pipefd[2]数组返回打开的读写描述符,pipefd[0]为读,pipefd[1]为写。

  第一个问题:文件描述符怎么会出现一个只能读,一个只能写呢?猜想是对一个文件打开了2次,一个以只读打开,一个以只写打开。使用fcntl来验证下:

       #include <unistd.h>
       #include <fcntl.h>

       int fcntl(int fd, int cmd, ... /* arg */ );
       F_GETFL (void)
              Get the file access mode and the file status flags; arg is ignored.

cmd为F_GETFL时,最后一个参数arg被忽略。测试代码:

 1 #include <sys/types.h>
 2 #include <sys/stat.h>
 3 #include <stdio.h>
 4 #include <fcntl.h>
 5 #include <signal.h>
 6 #include <unistd.h>
 7 #include <stdlib.h>
 8 
 9 int main(void)
10 {
11     int flags;
12     int fd[2];
13 
14     if (pipe(fd) < 0)
15     {
16         perror("pipe error");
17     }
18 
19     flags = fcntl(fd[0], F_GETFL,0);
20     if ( flags < 0 )
21     {
22         perror("fcntl");
23         close(fd[0]);
24         close(fd[1]);
25     }
26     switch (flags & O_ACCMODE) 
27     {
28         case O_RDONLY:
29             printf("read only\n");
30             break;
31 
32         case O_WRONLY:
33             printf("write only\n");
34             break;
35 
36         case O_RDWR:
37             printf("read write\n");
38             break;
39 
40         default:
41             printf("unknown access mode\n");
42     }
43 
44     flags = fcntl(fd[1], F_GETFL,0);
45     if ( flags < 0 )
46     {
47         perror("fcntl");
48         close(fd[0]);
49         close(fd[1]);
50     }
51     switch (flags & O_ACCMODE) 
52     {
53         case O_RDONLY:
54             printf("read only\n");
55             break;
56 
57         case O_WRONLY:
58             printf("write only\n");
59             break;
60 
61         case O_RDWR:
62             printf("read write\n");
63             break;
64 
65         default:
66             printf("unknown access mode\n");
67     }
68     close(fd[0]);
69     close(fd[1]);
70     exit(0);
71 }
View Code

相关文章:

  • 2021-06-09
  • 2021-11-17
  • 2021-07-19
  • 2021-11-30
  • 2021-09-05
  • 2022-02-19
  • 2021-04-13
  • 2022-01-16
猜你喜欢
  • 2022-12-23
  • 2021-10-19
  • 2021-07-04
  • 2021-05-19
  • 2021-07-02
  • 2021-11-18
  • 2021-04-11
相关资源
相似解决方案