passing pipe to threads

Posted by alaamh on Stack Overflow See other posts from Stack Overflow or by alaamh
Published on 2010-05-02T10:10:00Z Indexed on 2010/05/02 10:17 UTC
Read the original article Hit count: 263

Filed under:
|
|

I see it's easy to open pipe between two process using fork, but how we can passing open pipe to threads. Assume we need to pass out of PROGRAM A to PROGRAM B "may by more than one thread", PROGRAM B send his output to PROGRAM C

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

struct targ_s {
    int fd_reader;
};

void *thread1(void *arg) {

    struct targ_s *targ = (struct targ_s*) arg;
    int status, fd[2];
    pid_t pid;

    pipe(fd);
    pid = fork();

    if (pid == 0) {

        dup2(STDIN_FILENO, targ->fd_reader);

        close(fd[0]);
        dup2(fd[1], STDOUT_FILENO);
        close(fd[1]);

        execvp ("PROGRAM B", NULL);
        exit(1);
    } else {
        close(fd[1]);
        dup2(fd[0], STDIN_FILENO);
        close(fd[0]);

        execl("PROGRAM C", NULL);
        wait(&status);

        return NULL;
    }
}

int main(void) {


    FILE *fpipe;
    char *command = "PROGRAM A";
    char buffer[1024];

    if (!(fpipe = (FILE*) popen(command, "r"))) {
        perror("Problems with pipe");
        exit(1);
    }

    char* outfile = "out.dat";
    FILE* f = fopen (outfile, "wb");
    int fd = fileno( f );

    struct targ_s targ;
    targ.fd_reader = fd;

    pthread_t thid;
    if (pthread_create(&thid, NULL, thread1, &targ) != 0) {
        perror("pthread_create() error");
        exit(1);
    }

    int len;
    while (read(fpipe, buffer, sizeof (buffer)) != 0) {
        len = strlen(buffer);
        write(fd, buffer, len);
    }

    pclose(fpipe);

    return (0);
}

© Stack Overflow or respective owner

Related posts about c

    Related posts about multithreading