这是重定向fork和execvp派生的子级的输出的错误方法吗
Is this an incorrect way of redirecting the output of a child spawned by fork and execvp?
我正在尝试这样做:
int main(int argc, char** argv)
{
bool foo = false;
//parse args, check if --foo is an arg, if so mark foo true
if (foo)
{
//child behavior
while (true) { std::cout << "child" << std::endl; sleep(1); }
}
else
{
//do some parent process stuff
pid_t pid = fork();
if(pid == 0) //spawn child
{
char* newArgv[argc+1];
for (int i = 0; i < argc; ++i) newArgv[i] = argv[i];
newArgv[argc] = "--foo"; //make child run child code
std::ostringstream oss;
oss << argv[0] << " >> foo.txt 2>&1"; //same binary but redir child output
execvp(out.str().c_str(), newArgv);
}
//more regular parent code
}
return 0;
}
因此,基本上,二进制产生了一个新的参数,以不同的方式运行,并且输出被重定向(理想情况下)。不幸的是,虽然这确实产生了两个过程,但我似乎失去了孩子的输出,我不知道为什么?
更简单的有什么问题:
int main(int argc, char** argv) {
//do some parent process stuff
pid_t pid = fork();
if(pid == 0) //this is the child
{
//child behavior
while (true) { std::cout << "child" << std::endl; sleep(1); }
} else {
//more regular parent code
}
return 0;
}
在调用execv
之前,必须将文件描述符1设置为指向foo.txt
。然后,子进程将使用foo.txt
作为标准输出:
fd_t f = open("foo.txt", O_WRONLY);
if (f != 1)
{
close(1);
dup2(f, 1);
close(f);
}
execv(...);
上面代码中的任何错误修复都留给读者练习。Bugfixing包括但不限于检查函数调用返回的错误。
编辑:
如果你想让标准错误(过滤器描述符2)出现在标准输出的任何地方,你必须在execv
:之前添加它
close(2);
dup2(1, 2);
相关文章:
- 输出错误,问题是找到总和5000位数字cpp
- 使用复制构造函数的程序输出错误
- 异或字符串加密/解密输出错误
- 在linux上使用g++输出错误,在windows上更正
- 使用递归函数 (c++) 将长字符串转换为整数时输出错误
- ECDSA 密钥对生成输出错误
- fscanf() 输出错误的值
- 输入 1024 后十进制到二进制转换的输出错误?
- 输出错误命令的条件语句
- cuSparse (cusparseDcsrgemm) 中的矩阵乘法输出错误的结果
- 为什么 du -sh 输出错误大小的内存映射文件
- VS2017 的输出错误,但 mingw 有效
- 如何使FFMPEG C 代码不输出错误消息
- 乘以时输出错误.这是我编译器中的错误吗?C
- 输出错误:两个不同编译器上的不同输出:Prime Cryptarithm USACO
- 为什么输出错误崩溃
- C++输入/输出错误
- 尝试用 c++ 制作一个简单的加法器.编译成功,但输出错误
- 当我使用此合并排序代码运行时,输出错误
- 递归功能输出错误的值