C - dup2 stdin使dup2 stdout和stderr停止打印

时间:2017-01-16 23:42:12

标签: c

我有一个奇怪的问题。我目前正在创建两个程序,一个将在后台执行,另一个将读取其输出,并允许输入另一个在后台运行的程序。

问题是,当我将行dup2(in, STDIN_FILENO)放在后台执行的程序停止打印到文件时。

读者:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
int main()
{

    int out, err, in;
    size_t i = 0, j = 0;
    int offErr = 0, offOut = 0;
    char bufErr[1024];
    char bufOut[1024];
    char *cFifo = "/tmp/out";
    char *cFifoErr = "/tmp/err";
    char *cFifoIn = "/tmp/in";

    out = open(cFifo, O_RDONLY|O_CREAT, 0600);

    err = open(cFifoErr, O_RDONLY|O_CREAT, 0600);

    in = open(cFifoIn, O_WRONLY|O_CREAT, 0600);


    while(1)
    {
        memset(bufOut, 0, 1024);
        memset(bufErr, 0, 1024);
        i=0;
        j=0;
        while(!i && !j)
        {
            j = pread(err, bufErr, 1024, offErr);
            i = pread(out, bufOut, 1024, offOut);
            offOut +=i;
            offErr +=j;
        }
        if(i)
            write(STDOUT_FILENO, bufOut, 1024);
        if(j)
            write(STDOUT_FILENO, bufErr, 1024);

    }
    return 0;
}

和作家(背景):

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
int main()
{
    int out, in, err;

    char *cFifo = "/tmp/out";
    char *cInFifo = "/tmp/in";
    char *cErrFifo = "/tmp/err";

    out = open(cFifo, O_RDWR|O_CREAT|O_TRUNC, 0600);
    in = open("/tmp/in", O_RDWR|O_CREAT|O_TRUNC, 0600);
    err = open(cErrFifo, O_RDWR|O_CREAT|O_TRUNC, 0600);

    dup2(out, STDOUT_FILENO);
    dup2(err, STDERR_FILENO);
    //dup2(in, STDIN_FILENO); //if  I uncomment this it stops printing to out or err

    system("python");

    while(1);
    return 0;
}

1 个答案:

答案 0 :(得分:0)

取消注释时:

//dup2(in, STDIN_FILENO); //if  I uncomment this it stops printing to out or err

你正在从一个空文件中读取Python(当你打开它时它被创建和/或截断),所以Python无所事事并退出。

您的阅读器代码然后位于while (1) ;循环中,没有任何用处。

至少,在printf()语句后添加system(),以便知道Python命令何时完成。