如果stdout已经关闭,是否可以重新打开它。
例如下面的代码。
#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 outputn");
perror("standard error");
}
输出:标准错误:错误的文件描述符
有没有办法在test2.c 中打开stdout
首先,需要注意的是,您只需将fd 1设置为CLOEXEC,因此它当然会在'execve'调用时关闭。确保你理解这一点。如果您能够编辑"test1",则只需删除"fcntl"调用即可。
但是,另一方面,如果你根本不能编辑"测试"1,可能有一些方法可以绕过它
-
如果"stdout"one_answers"stderr"指向同一个位置(可能它们最初是?(,则可以使用以下调用将fd=2复制为1:
dup2(2,1)
。 -
(特定于Linux(如果在"execve"之前以某种方式调用了"fork",则可以使用
procfs
文件系统访问关闭的fd。假设"test2"的父进程具有要在fd=1中打开的"stdout",则可以使用getppid()
获取其PID,然后打开/proc/<ppid>/fd/1
(当然还有-dup2
,将生成的fd转换为1
(。
否则-可能无法"重新打开"文件描述符-因为它已关闭。显然,从现在起,您可以始终open
您希望stdout
指向的文件(dup2
它到1
!(,并避免"坏文件描述符"错误。
祝你好运!