簡體   English   中英

在Linux中使用dup2()和create()在循環內進行重定向

[英]Redirection in Linux with dup2() and create() inside a loop

我正在運行下面的代碼,並且無法重定向到文件。 文件已制成,但沒有放入任何文件。 如果刪除最后一個dup2(saveout,1)語句,則可以創建並寫入該文件,但是無法返回到終端,這一點很重要。 一旦將dup2(saveout,1)放回我的代碼中,重定向就會停止,但是我可以回到終端。 我不明白為什么會這樣。 我想重定向並返回到終端。

main.cpp

#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string>
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
using namespace std;

void printmessage() {
    printf("this is the message\n");
}

int main(int argc, char** argv) {    
    int saveout;
    int fd;
    saveout = dup(1);

    for (int i = 0; i < 10; i++) {
        fd = creat("/home/carl/example.txt",O_CREAT|O_APPEND);
        dup2(fd, 1);
        close(fd);
        printf("Testing the message");
        printmessage();

       dup2(saveout,1);
       close(saveout);
    }
    return 0;
}

這是一個文件權限問題,您應該閱讀所使用功能的手冊頁。

creat() takes as first argument the filename, and as second the file creation rights, not its opening mode.

creat()函數是一個簡單的open()調用,帶有一些特定的標志,因此您只需要設置權限即可。

如果要打開文件,如果不存在則創建文件,請使用

open(filename, O_CREAT | O_RDWR | O_APPEND, 0600) for example, or
creat(filename, 0600),

這幾乎是等效的,但是您將無法附加文本,因為“ creat()等同於帶有等於O_CREAT | O_WRONLY | O_TRUNC的標志的open()”

默認情況下, printf是緩沖的。 (逐行輸出到tty,也許輸出到其他內容的方式有所不同)。 在兩次調用dup2(..., 1) ,都應使用fflush沖洗:

fflush(stdout);

第二個dup2(saveout,1); 將因為您關閉saveout失敗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM