c ++管道缓冲禁用

时间:2018-04-03 07:15:26

标签: c++ linux pipe

如何在管道中禁用缓冲。我正在为I / O创建一个简单的录音机/播放器。要做到这一点,我需要记录输出时间延迟。

要记录延迟,我需要这样的东西

example tekst
"wait 1s"
example tekst
"wait 1s"
example tekst
...

但如果我使用

pipe2(in, O_DIRECT );

我看到类似的东西

"wait 100s"
"100 times" example tekst
"wait 100s"
"100 times" example tekst
...

man7告诉:

   O_DIRECT (since Linux 3.4)
          Create a pipe that performs I/O in "packet" mode.  Each
          write(2) to the pipe is dealt with as a separate packet, and
          read(2)s from the pipe will read one packet at a time.

我尝试通过以下方式禁用缓冲:

fcntl(in[1], F_SETPIPE_SZ, 1);

但它仍无效。

read.cpp

#define _GNU_SOURCE
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <poll.h>
#include <assert.h>
bool keep = true;

void intHandler(int dummy) {
    keep = 0;
}

int main(void) {
    signal(SIGINT, intHandler);
    int in[2];
    int out[2];
    int pid;
    int fo;
    char buf[1024];
    pipe2(in, O_DIRECT );
    pipe2(out, O_DIRECT );
    pid = fork();
    if (pid == -1) {
        perror("fork");
        exit(1);
    }

    if (pid == 0) {
        close(in[0]);
        close(out[1]);
        close(0);
        close(1);
        dup2(in[1], 1);
        dup2(out[0], 0);
        close(in[1]);
        close(out[0]);
        sleep(1);
        char *newargv[] = {"/root/Pulpit/a1", NULL, NULL, NULL};
        char *newenviron[] = {NULL};
        int ret = execve("/root/Pulpit/a1", newargv, newenviron);
        printf("%d", ret);
        return 0;
    } else {
        close(out[0]);
        close(in[1]);
        int n = 0;
        while (keep) {
            int wyn = read(in[0], buf, 1024);
            if (wyn > 0) {
                char aa[1024];
                write(1, buf, wyn);
                fsync(1);
            }
        }
    }
    return (0);
}

a1.cpp

#include <cstdlib>
#include <unistd.h>
#include "stdio.h"

using namespace std;

/*
 *
 */
int main(int argc, char** argv) {
    while(true){
    printf("example text\n");
    usleep(100000);
    }
    return 0;
}

0 个答案:

没有答案