c++ -/proc/fd 文件描述符显示什么?

标签 c++ linux posix

了解 /proc/今天的目录,特别是我对将有关进程的所有信息半公开可用的安全影响感兴趣,因此我编写了一个简单的程序来执行一些简单的诸如此类的事情,使我能够探索 /proc/ 的一些属性。目录:

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

using namespace std;

extern char** environ;

void is_linux() {
#ifdef __linux
   cout << "this is running on linux" << endl;    
#endif
}

int main(int argc, char* argv[]) {
  is_linux();

  cout << "hello world" << endl;
  int fd = open("afile.txt", O_RDONLY | O_CREAT, 0600);
  cout << "afile.txt open on: " << fd << endl;

  cout << "current pid: " << getpid() << endl;;

  cout << "launch arguments: " << endl;
  for (int index = 0; index != argc; ++index) {
    cout << argv[index] << endl;
  }

  cout << "program environment: " << endl;
  for (char** entry = environ; *entry; ++entry) {
    cout << *entry << endl;
  }

  pause();
}

有趣的是(无论如何对我来说),当我检查文件描述 rune 件夹 ( /pid/<PID#>/fd ) 时,我看到了这个:

root@excalibur-VirtualBox:/proc/1546/fd# ls -l
total 0
lrwx------ 1 root root 64 Nov  7 09:12 0 -> /dev/null
lrwx------ 1 root root 64 Nov  7 09:12 1 -> /dev/null
lrwx------ 1 root root 64 Nov  7 09:12 2 -> /dev/null
lrwx------ 1 root root 64 Nov  7 09:12 3 -> socket:[11050]

为什么文件描述符指向/dev/null ?这是为了防止用户能够将内容注入(inject)文件而实际上不是进程本身,还是我不基于此?更奇怪的是,为什么打开文件的文件描述符指向套接字?这看起来真的很奇怪。如果有人能为我阐明这一点,我将不胜感激。谢谢!

最佳答案

你肯定看错了/proc目录(对于其他 PID 或在另一台计算机上)。 /proc/<pid>/fd的内容您的程序应该如下所示:

lrwx------ 1 user group 64 Nov  7 22:15 0 -> /dev/pts/4
lrwx------ 1 user group 64 Nov  7 22:15 1 -> /dev/pts/4
lrwx------ 1 user group 64 Nov  7 22:15 2 -> /dev/pts/4
lr-x------ 1 user group 64 Nov  7 22:15 3 -> /tmp/afile.txt

在这里我们可以看到文件描述符 0、1 和 2 显示为指向程序运行的伪终端的符号链接(symbolic link)。可能是 /dev/null如果您使用输入、输出和错误重定向启动程序。文件描述符 #3 指向文件 afile.txt当前已打开。

关于c++ -/proc/fd 文件描述符显示什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26803362/

相关文章:

php - 将多个站点文件合并到一个位置

linux - Init.d 脚本导致启动挂起

macos - Mac OS X 10.5+ 和 POSIX

调用信号处理程序但仍然忽略信号 (Posix, C)

c++ - Win32 API : How to avoid flickering of basic window controls?

C++:成员引用还是指针?

linux - openSUSE 上的 lightdm 自动登录

c - 以与 "ls -l"命令相同的方式格式化日期/时间

c++ - 返回模板化结构对象指针时遇到问题

c++ - 当 unary_function 使用引用参数时使用 std::not1 编译时出错