首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >线程馈送其他MultiThreading

线程馈送其他MultiThreading
EN

Stack Overflow用户
提问于 2010-05-02 18:10:01
回答 1查看 133关注 0票数 0

我看到使用fork打开两个进程之间的管道很容易,但我们如何将打开的管道传递给线程。假设我们需要从程序A传递到程序B“可以由一个以上的线程”,程序B将其输出发送到程序C

编辑:我在修改代码后再次出现,以使代码更易于阅读。

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <fcntl.h>

void *thread1(void *arg) {

    int status, fd[2];
    pid_t pid;

    pipe(fd);
    pid = fork();

    if (pid == 0) {
        int fd2 = *((int *) (arg));
        dup2(STDIN_FILENO, fd2);

        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 );

    int fd[2];
    fd[0] = open(outfile, O_WRONLY);

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

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

    pclose(fpipe);

    return (0);
}
EN

回答 1

Stack Overflow用户

发布于 2010-05-02 18:35:15

对于进程内消息传递,POSIX队列可能比管道更适合您的需要。查看man mq_overview (或online)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2753089

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档