簡體   English   中英

將stdout重定向到文件的過程在中間停止。 Linux的

[英]Redirecting stdout to file stops in the middle. Linux

我的程序使用“ system”命令通過以下方式啟動兩個二進制文件:

int status = system("binaryOne &");
int status = system("binaryTwo &");

由於所有三個二進制文件都寫入相同的stdout,因此所有輸出都是混合的並且難以理解。 因此,我更改了啟動命令,將兩個二進制文件的stdout重定向到執行tail -f的不同文件:

int status = system("binaryOne > oneOut.txt &");
int status = system("binaryTwo > twoOut.txt &");

問題在於寫入文件的操作有時會停止。 有時,它凍結,緩沖在某處,而不是一部分被拋回。 大多數時候,它只是停止。

我確認二進制文件繼續運行並寫入stdout。

這是您可以使用fork + exec嘗試的方法

pid_t child_pid = fork();

if (!child_pid) {
    // child goes here

    char * args[] = {"binaryOne", NULL};

    int fd = open("oneOut.txt", O_WRONLY | O_CREAT | O_TRUNC);

    if (!fd) {
        perror("open");
        exit(-1);
    }

    // map fd onto stdout
    dup2(fd, 1);

    // keep in mind that the children will retain the parent's stdin and stderr
    // this will fix those too:
    /*
    fd = open("/dev/null", O_RDWR);
    if (!fd) {
        perror("open");
        exit(-1);
    }

    // disable stdin
    dup2(fd, 0);
    // disable stderr
    dup2(fd, 2);
    */

    execvp(*args, args);

    // will only return if exec fails for whatever reason
    // for instance file not found

    perror("exec");

    exit(-1);
}

// parent process continues here

if(child_pid == -1) {
    perror("fork");
}

重要說明:忘記將寫標志設置為open

您可以使用popen()避免大多數情況。 每個popen調用都會為您的主程序設置一個單獨的管道以供讀取,並且輸出不會交織在一起,因為它將所有內容定向到stdout。 而且顯然不如寫入文件和拖尾文件那么笨拙。 僅出於您的目的,這是否比fork/exec更好。

暫無
暫無

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

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