简体   繁体   中英

Read from stdout fd of a running process in C

After much search and confusion i have to ask....

I have a binary running that continuously writes to stdout forever in a infinite loop.

fprintf(stdout,"%s\n",msg);

Lets call it generator.

The generator sends its PID (by using getpid() ) to another binary called collector.

As soon as the collector receives the PID it visits procfs

#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>

#define MAX_BUF 1024

int main()
{
    int fd;
    char *generator_fd = "/proc/17163/fd/1"; //This is the process ID sent by generator
    char buf[MAX_BUF];

    fd = open(generator_fd, O_RDONLY);
    read(fd, buf, MAX_BUF);
    printf("Received: %s\n", buf);
    close(fd);
    return 0;
}

But it prints nothing :(. Can anyone help

File descriptors are local to the process concerned. You can't read an fd belonging to another process like that. What's in /proc/NNNN/fd/NN is a symlink to the file / device that was opened. If this is (eg) a tty, opening it is probably going to fail, but is certainly not going to give you what was written to the tty by the generator.

It sounds to me like you want a pipe between the processes.

Thanks everyone for the info. I am going to use named pipes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM