0

The code is following.

Q1:

If dup2(fd3, STDOUT_FILENO), string2 will be in log.txt.

If dup2(g_ctl[0], STDOUT_FILENO), string2 won't be received by g_ctl[1]. string1 and ls -al output will be received, Why ?

Q2:

The third library have some stdout/stderr log, if using dup2(socket_fd, STDOUT_FILENO), all logs will be collected by socket. But I also want to print all logs to screen at the same time, how to do it?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>

static pthread_t g_pid;
static int g_ctl[2] = {-1, -1};

void *_run_loop(void *args) {
    char buf[1024];
    int n;
    while (1) {
        n = recv(g_ctl[1], buf, 1024, 0);
        if (n > 0) {
            fprintf(stderr, "%.*s\n", n, buf);
        }
    }
}

int main(int argc, char const *argv[])
{
    int fd3 = open("./log.txt", O_CREAT | O_RDWR | O_APPEND, 0666);

    int ret = socketpair(AF_UNIX, SOCK_STREAM, 0, g_ctl);
    assert(ret == 0);

    ret = dup2(g_ctl[0], STDOUT_FILENO);
    assert(ret > 0);

    pthread_create(&g_pid, NULL, _run_loop, NULL);

    send(STDOUT_FILENO, "string1", 5, 0);
    system("ls -al");

    printf("string2\n");

    sleep(5);

    return 0;
}
oguz ismail
  • 1
  • 16
  • 47
  • 69
Kathy.Pu
  • 97
  • 6

1 Answers1

0

Q1: You need to fflush(stdout); after your printf. Otherwise printf may buffer your output. It will be written when your program exits if it hasn't already, but by that time your reading thread has already been canceled, so you don't get to read it.

Q2: As far as I know, the only way to get your output written to two files is to actually write it to both file descriptors. There is no way in Unix to "double-dup" a file descriptor. Even a command like tee is really just calling write() twice for each chunk of data read. You can do it manually, or inside a function, or in a thread, but you have to do it.

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82