从阅读中选择块fifo

时间:2016-02-10 19:42:43

标签: c linux fifo

在尝试从fifo读取时,我遇到了read()阻止我的程序的问题。我希望我的程序从多个文件描述符中读取,并且当其中包含信息时,它会将其写入标准输出。

我尝试使用select但似乎没有用。

main.c(第二个程序有n个)

for(i=0;i<n;i++)
{
    fd[i] = open(myfifo[i], O_RDWR);
    printf("%s\n",myfifo[i]);
}
while(1)
{
        for(i=0;i<n;i++)
        {
            FD_ZERO(&set);
            FD_SET(fd[i], &set);
            n = select(fd[i]+1, &set, NULL, NULL, NULL);
            if (n > 0)
            {   
                r = read(fd[i], &demon1, sizeof(demon1));
                if(r !=-1)
                {
                    /*READ DATA*/
                }
            }
        }      
}

第二个程序(这个程序有n个)

void signal_handler(int signum)
{
if (signum == SIGUSR1)
{
    /*STAFF*/
    mkfifo(myfifo, 0666);
    fd = open(myfifo, O_RDWR);
    write(fd, &demon1 , sizeof(demon1));
    close(fd);
}
}

每个程序都有名为myfifo1的myo,myfifo2 ..等等。 请帮忙。

编辑:现在我有了这个:

int max_fd;
while(1)
{
FD_ZERO(&set);
for(i=0;i<n;i++)
{
    FD_SET(fd[i], &set);
    if (fd[i]>max_fd) max_fd = fd[i];
}
n = select(max_fd+1, &set, NULL, NULL, NULL);
if (n != 0)
{   
    int d;
    for (d = 0; d<FD_SETSIZE; d++) 
    {
        if (FD_ISSET(d,&set))
        {
            r = read(d, &demon1, sizeof(demon1));
            if(r !=-1)
            {
               /*CODE*/
            }
        }
    }
}
}

只在第一次尝试时读取正确,稍后只能读取第一个文件描述符

显然

之间存在差异
 //n = select(max_fd+1, &set, NULL, NULL, NULL);
 //if (n != -1)

    if (select(max_fd+1, &set, NULL, NULL, NULL) != -1)
编辑:它似乎只适用于ubuntu虚拟机.. linux薄荷笔记本电脑没有。

1 个答案:

答案 0 :(得分:1)

不,你应该建立一个阅读集,然后进行选择呼叫:

// Create the set of descriptor to select on
FD_ZERO(&set);
max_fd = 0;
for (i=0; i<n; i++) {
    FD_SET(fd[i], &set);              // add the descriptor to the set
    if (fd[i]>max_fd) max_fd = fd[i]; // register the highest descriptor
}

// Then select on the set of descriptors
if (select(max_fd+1, &set, NULL, NULL, NULL)!=-1) {
    // extract which descriptors are available for reading
    for (int d=0; d<FD_SETSIZE; d++) {
        if (FD_ISSET(d,&set)) {
            // something to read in descriptor d
        }
    }
}
相关问题