[英]Redirecting exec output to a buffer or file
我正在編寫一個 C 程序,其中我fork()
、 exec()
和wait()
。 我想將我執行的程序的輸出寫入文件或緩沖區。
例如,如果我 exec ls
我想將file1 file2 etc
寫入緩沖區/文件。 我認為沒有辦法讀取標准輸出,這是否意味着我必須使用管道? 這里有我找不到的一般程序嗎?
將輸出發送到另一個文件(我省略了錯誤檢查以關注重要細節):
if (fork() == 0)
{
// child
int fd = open(file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
dup2(fd, 1); // make stdout go to file
dup2(fd, 2); // make stderr go to file - you may choose to not do this
// or perhaps send stderr to another file
close(fd); // fd no longer needed - the dup'ed handles are sufficient
exec(...);
}
用於將輸出發送到管道,以便您可以將輸出讀入緩沖區:
int pipefd[2];
pipe(pipefd);
if (fork() == 0)
{
close(pipefd[0]); // close reading end in the child
dup2(pipefd[1], 1); // send stdout to the pipe
dup2(pipefd[1], 2); // send stderr to the pipe
close(pipefd[1]); // this descriptor is no longer needed
exec(...);
}
else
{
// parent
char buffer[1024];
close(pipefd[1]); // close the write end of the pipe in the parent
while (read(pipefd[0], buffer, sizeof(buffer)) != 0)
{
}
}
你需要准確地決定你想做什么——最好解釋得更清楚一點。
如果您知道要將執行命令的輸出轉到哪個文件,則:
如果您希望父級讀取子級的輸出,請安排子級將其輸出通過管道傳回父級。
由於您看起來將在 linux/cygwin 環境中使用它,因此您想使用popen 。 這就像打開一個文件,只有你會得到正在執行的程序stdout
,所以你可以使用你正常的fscanf
, fread
等。
fork 后,使用dup2(2)
將文件的 FD 復制到 stdout 的 FD 中,然后執行。
您還可以使用 linux sh
命令並向其傳遞包含重定向的命令:
string cmd = "/bin/ls > " + filepath;
execl("/bin/sh", "sh", "-c", cmd.c_str(), 0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.