如何使用 C 中的 execl() 函数在文件中打印 stderr 消息



例如:用于在文件中写入 stderr 消息的命令是

command > /dev/null 2>text.file"

所以

execl("gcc" , "gcc" , "-g" , "test.c" , ">" , "/dev/null 2" , ">" , "test" , NULL);

execl 返回 -1。它不是文本文件中的打印错误

流重定向功能由 shell 提供,不是执行命令的标准方法。

你可以

做的是启动一个shell(如bash),然后你可以通过传递你的命令从中重定向stdrr。

execl("/bin/bash", "bash", "-c", "gcc -g test.c > /dev/null 2>test", NULL);

试试这个:

#include<unistd.h>
#include<fcntl.h>
//Remaining code till here
dup2(open("/dev/null",O_WRONLY), 1); //redirect stdout to /dev/null
dup2(open("text.file",O_WRONLY), 2); //redirect stderr to text.file
execl("gcc" , "gcc" , "-g" , "test.c", NULL);

注意:您可能需要为 text.file 添加O_CREAT标志。

最新更新