面试题答案
一键面试子进程对文件描述符fd的权限情况
在多进程环境下,当父进程打开一个文件获得文件描述符fd并设置了特定权限后,子进程会继承父进程的文件描述符。这意味着子进程对该文件描述符fd具有与父进程相同的权限。这是因为子进程是父进程的副本,继承了父进程的用户空间内存、打开的文件描述符等资源。
希望子进程对文件描述符有不同权限的操作及原理
要让子进程对文件描述符有不同的权限,可以在子进程中使用 fcntl
函数来修改文件描述符的权限。fcntl
函数可以对已打开的文件描述符执行各种控制操作,包括改变文件状态标志等。
例如,如果希望子进程将文件描述符设置为只读权限,即使父进程可能有读写权限,可以在子进程中使用 fcntl
将文件描述符的状态标志设置为只读。
代码示例
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
int main() {
// 以读写权限打开文件
int fd = open("test.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (fd == -1) {
perror("open");
return 1;
}
pid_t pid = fork();
if (pid == -1) {
perror("fork");
close(fd);
return 1;
} else if (pid == 0) {
// 子进程
// 将文件描述符设置为只读权限
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1) {
perror("fcntl F_GETFL");
close(fd);
return 1;
}
flags &= ~O_WRONLY; // 清除写权限
if (fcntl(fd, F_SETFL, flags) == -1) {
perror("fcntl F_SETFL");
close(fd);
return 1;
}
// 子进程进行只读操作
char buf[100];
ssize_t read_bytes = read(fd, buf, sizeof(buf));
if (read_bytes == -1) {
perror("read");
close(fd);
return 1;
}
buf[read_bytes] = '\0';
printf("Child process read: %s\n", buf);
close(fd);
} else {
// 父进程
// 父进程进行读写操作
const char* msg = "Hello, world!";
ssize_t write_bytes = write(fd, msg, strlen(msg));
if (write_bytes == -1) {
perror("write");
close(fd);
return 1;
}
close(fd);
wait(NULL); // 等待子进程结束
}
return 0;
}
在上述代码中:
- 父进程以读写权限打开文件
test.txt
。 - 创建子进程后,子进程通过
fcntl
函数修改文件描述符的权限为只读。 - 父进程向文件写入内容,子进程从文件读取内容,展示了不同权限下的操作。