【发布时间】:2019-11-16 11:45:18
【问题描述】:
如果标准输出已经关闭,是否可以重新打开它。
例如下面的代码。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
int main(){
fcntl(1,F_SETFD,FD_CLOEXEC) ;
execve("./test2",NULL, NULL);
printf("Can you see me [TWO]\n");
}
以上代码关闭标准输出文件描述符,然后调用 execve。 test2的代码如下
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
int main() {
printf(" standard output\n");
perror("standard error");
}
输出: 标准错误:错误的文件描述符
有什么方法可以在 test2.c 中打开标准输出
【问题讨论】:
-
我猜你的用例比 mcve 复杂一点...在执行之前使用
dup复制stdout。执行并关闭后,在您的副本上使用dup2使fd 1 再次指向stdout。