使用 open() 和 close() 重定向输入

redirect input using open() and close()

我正在尝试了解 I/O 进程间机制的工作原理。 我试过 运行 这个代码:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
...
char *const paramList[] = {"/bin/cat"};
close(0);
open("./my_file", O_RDONLY);
execv("/bin/cat",paramList);
...

但没有任何进展。 (虽然它编译)

我做错了什么,我的代码做了什么?

根据 docs for execv:

The array of pointers must be terminated by a NULL pointer.

因此,将 NULL 添加到 paramList 的末尾。

如果您仍然遇到问题,请确保检查所有系统调用的 return 值,并查看是否有任何调用失败。