Linux/Unix 系统编程与 C++ 控制台输入输出
1. 编写自定义 shell 的基础操作
在 Linux/Unix 系统编程中,我们可以使用系统调用编写自定义 shell。例如,使用 execvp 函数来执行命令:
const char *argv[] = {"ls", nullptr};
execvp("ls", const_cast<char **>(argv));
这里使用 PATH 环境变量来定位 ls 命令。
为了捕获子进程的输出,我们可以使用 Unix 管道进行进程间通信(IPC)。以下是一个示例代码:
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <array>
#include <iostream>
#include <string_view>
class mypipe
{
std::array<int, 2> m_handles;
public:
mypipe()
{
if (pipe(m_handles.data()) < 0) {
exit(1);
}
}
~mypipe()
{
超级会员免费看
订阅专栏 解锁全文
2万+

被折叠的 条评论
为什么被折叠?



