❶ C语言中p和p2函数的不同和使用
p返回的新文件描述符一定是当前可以用描述符中的最小值。下面先打开一个文件来看下文件描述符,为保证测试成功,创建一个测试文件log.txt。
1
2
3
4
5
6
7
8
9
10
11
12
#include <fcntl.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
int fd;
fd = open("./log.txt", O_RDWR);
printf("%d\n", fd);
return 0;
}
上面的代码用读写打开了log.txt这个文件,编译上面的代码然后执行,执行成功的话,应当是输出3,因为0,1,2分别被标准输入,标准输出,标准错误输出占用了。使用p复制这个文件描述符,并尝试移动fd偏移量:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
int fd, fd;
fd = open("./log.txt", O_RDWR);
//复制fd
fd = p(fd);
//输出fd,应当为4
printf("%d\n", fd);
//打印出fd和fd的偏移量,都为0
printf("%d\n", (int)lseek(fd, 0, SEEK_CUR));
printf("%d\n", (int)lseek(fd, 0, SEEK_CUR));
//将fd的偏移量+3
lseek(fd, 3, SEEK_SET);
//打印出fd和fd的偏移量,都为3
printf("%d\n", (int)lseek(fd, 0, SEEK_CUR));
printf("%d\n", (int)lseek(fd, 0, SEEK_CUR));
return 0;
}
编译执行上例代码可以发现当移动fd的偏移量时,fd的偏移量也发生了变化。往文件里写入内容试试,先把log.txt内容清空。
❷ linux 下 pipe()与p2 问题
#include<stdio.h>
#include<unistd.h>
intmain()
{
intfd[2];
pipe(fd);
if(fork()==0){
close(fd[0]);
p2(fd[1],STDOUT_FILENO);
close(fd[1]);
printf("Hello");
printf("123");
printf("ooppqq");
}else{
close(fd[1]);
#defineBUFFER_SIZE1024
charbuffer[BUFFER_SIZE];
intreadCount;
while((readCount=read(fd[0],buffer,
BUFFER_SIZE-1))>0){
buffer[readCount]='