【问题标题】:Ncurses with non-blocking input and fork具有非阻塞输入和分叉的 Ncurses
【发布时间】:2011-09-19 06:40:40
【问题描述】:

我在使用 fork() 和 ncurses 的进程之间进行正确的读写时遇到问题。我有一个控制应用程序输入的进程(我称之为儿子),还有一个控制应用程序逻辑的进程(父进程)。

我的问题是我在管道内写入以将信息从儿子发送给父母,但父母没有读取任何内容。

由于非阻塞性质,我在读写时添加了等待和信号以相互排除进程。

让我给你看一些代码:)

    //---- pipes, read i write no bloquejants ---------
    int flags_f0 = fcntl(pip_fill[0],F_GETFL);
    int flags_f1 = fcntl(pip_fill[1],F_GETFL);
    int flags_p0 = fcntl(pip_pare[0],F_GETFL);
    int flags_p1 = fcntl(pip_pare[1],F_GETFL);
    int flags_read = fcntl(0,F_GETFL);
    int flags_write = fcntl(1,F_GETFL);


    fcntl(pip_fill[0],F_SETFL,flags_f0 | O_NONBLOCK);
    fcntl(pip_fill[1],F_SETFL,flags_f1 | O_NONBLOCK);
    fcntl(pip_pare[0],F_SETFL,flags_p0 | O_NONBLOCK);
    fcntl(pip_pare[1],F_SETFL,flags_p1 | O_NONBLOCK);
    fcntl(0,F_SETFL,flags_read | O_NONBLOCK);
    fcntl(1,F_SETFL,flags_write | O_NONBLOCK);
    //-------------------------------------------------

    //---- semàfors ----
    int id_Sem;

    id_Sem = shmget (IPC_PRIVATE, sizeof(int), IPC_CREAT | 0600);
    if (id_Sem == -1)
    {
        write(2,"Error!\n",7);
        Sortir(&ll_a_r,&ll_res,&ll_mis,&ll_n_mis,&c,&c_write);
        exit (0);
    }


if(SEM_constructor(&sem1) < 0)
{
       shmctl(id_Sem, IPC_RMID, NULL);
    }

    if(SEM_constructor(&sem2) < 0)
{
        shmctl(id_Sem, IPC_RMID, NULL);
        SEM_destructor (&sem1);
    }

    SEM_init (&sem1, 0);
    SEM_init (&sem2, 0);

//------------------



//la primera vegada que entri en el fill posarem les següents dades a la var valor

Afegir_Cadena(&c,"M0:");    //on M0: menú principal

pantalla(w);
pinta_menu_principal(w,a_menus);    //pinta el menú principal per pantalla

pid = fork();

switch (pid)
{
    case -1: //ERROR
        write(2,"Error!\n",7);
        Sortir(&ll_a_r,&ll_res,&ll_mis,&ll_n_mis,&c,&c_write);
        exit(-1);
            break;

    case 0: //FILL
        close(pip_fill[0]); //tanquem l'extrem de la pipe que no usem (la de lectura)
        close(pip_pare[1]); //tanquem l'extrem de la pipe que no usem (la d'escriptura)

        while(1)
        {
                cc = getch();
                if(cc != ERR)
            {
                if(cc == 0x0A)
                {
                    printf("Enter [%s]\n", Retorna_Cad(&c_write));
                    SEM_wait (&sem1);
                    tmp = write(pip_fill[1],Retorna_Cad(&c_write),Retorna_Longitud(&c_write) + 1);  //el fill escriu a la pipe la variable c
                    SEM_signal (&sem1);                                                     //longitud + 1: el +1 es per el \0
                    //printf("Ret: %d",tmp);
                    Esborra_Cadena(&c_write);
                    actualitza_pantalla(w);
                }
                else
                {
                    Afegir_Caracter(&c_write,cc);
                    cc = ERR;
                }
            }

    //***** READ PARE *********
            SEM_wait (&sem2);
            nbytes = read(pip_pare[0],valor,256); //el fill llegeix de la pipe la var un cop ha estat tractada per el pare
            SEM_signal (&sem2);

            if (nbytes > -1)
            {   
                Inserir_Cad(&c,valor);
                //tractar el missatge del pare
        Tractar_Missatge_del_Pare(&ll_mis,&ll_res,&c,w,a_menus,&ll_a_r);
            }
        }
        break;

    default: //PARE
        close(pip_fill[1]); //tanquem l'extrem de la pipe que no usem (la d'escriptura)
        close(pip_pare[0]); //tanquem l'extrem de la pipe que no usem (la de lectura)

        while(1)
        {
            temps_inici = (float)clock();
            SEM_wait (&sem1);
            nbytes = read(pip_fill[0],valor,256);//el pare llegeix de la pipe la var c 
            SEM_signal (&sem1);

            if (nbytes > -1 || tmp > 0)
            {   //vol dir que hem llegit algo per la pipe pip_fill
                tmp++;
                Inserir_Cad(&c,valor);
                Tractar_Missatge_del_Fill (&ll_mis,&c,&ll_n_mis,w);
                SEM_wait (&sem2);
                   write(pip_pare[1],Retorna_Cad(&c),Retorna_Longitud(&c) + 1); //el pare escriu a la pipe la var tractada
                SEM_signal (&sem2);

                actualitza_pantalla(w);
            }


            temps_final = (float)clock();
            temps_per_bucle = (float)(temps_final - temps_inici) / (float)CLOCKS_PER_SEC;

            Esborra_Cadena(&aux);
            Afegir_Float (&aux, temps_per_bucle);
            //mvwprintw(w[4],8,1,Retorna_Cad(&aux));

        }
        break;
    }
}
else
    {
    exit(1);    //login incorrecte --> sortim de l'aplicacio
}

我没有发布所有代码,只有主要部分的读写是通过等待和信号完成的。

也许我正在失去一些我现在看不到的东西。事实是,儿子将在“pipe_fill”上写入,而父母将从该管道中读取,同样,父母将在“pipe_pare”上写入,然后儿子将从中读取以发送信息。

我也在使用 ncurses 来绘制所有的窗口。

感谢您的帮助:)

【问题讨论】:

  • 为什么不直接使用阻塞 I/O 而不是使用信号量呢?您的父母锁定信号量,尝试读取,失败,解锁,再次锁定,尝试读取等,而可怜的儿子永远没有机会写任何东西,因为它总是在等待SEM_wait
  • 如果我只阻塞 O/I,在儿子结束对同一管道的写入之前,父母可以从管道中读取吗?我认为我可以在父进程的末尾放置一个 sleep(1),但我不能在这个应用程序中使用这个函数:(
  • 阻塞 I/O 将完全符合您的要求。把你所有的信号量和 fcntl 扔掉。当你使用 stdio 时你不会做这些事情,你也不需要它。 read 将等到管道上有一些数据可用。不一定都是 256 个字节,但至少 1 个字节。
  • 我同意你的观点,但我需要一个非阻塞系统,我的意思是,我不需要父母等待管道中的某些东西。我认为在这种情况下我需要 fcntls 和信号量,因为互斥。如果我错了,请纠正我。
  • 你不需要信号量,因为你不需要互斥。你可能认为你想建立顺序:首先是作者,其次是读者。这不是互斥,也不能通过互斥机制来完成。但是您也不需要订单,管道会神奇地自行完成所有操作。如果你不想让读者等待,那么就去非阻塞(但是为什么你让它在 sema 上等待呢?)如果你去非阻塞,当没有输入时,读者必须有一些工作要做管道。它还需要知道何时必须停止执行该工作并返回检查管道。

标签: c fork pipe semaphore ncurses


【解决方案1】:

好的,这就是我想到的代码。

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

int main ()
{
  int pipePC[2];
  int pipeCP[2];

  pipe(pipePC);
  pipe(pipeCP);

  char buf[11];
  int n;

  switch (fork()) {
  case -1:
    exit (1);
    break;
  case 0: /* child */
    close(pipePC[1]);
    close(pipeCP[0]);
    while (1) { /* read, then write */
        n = read(pipePC[0], buf, 10); /* read the question */
        if (n > 0) {
            buf[n] = 0;
            printf ("child got '%s'\n", buf); /* calculate the answer here */
            write(pipeCP[1], "foobar", 6); /* write the answer */
        }
        else {
            printf ("child got nothing\n");
            exit (1);
        }
        sleep(2); /* only to slow down the output */
    }
    break;
  default: /* parent */
    close(pipePC[0]);
    close(pipeCP[1]);
    while (1) { /* write, then read */
        write(pipePC[1], "barfoo", 6); /* ask a question */
        n = read(pipeCP[0], buf, 10); /* get the answer */
        if (n > 0) {
            buf[n] = 0;
            printf ("parent got '%s'\n", buf);
        }
        else {
            printf ("parent got nothing\n");
            exit (1);
        }
        sleep(3); /* only to slow down the output */
    }
    break;
  }
}

【讨论】:

  • 有了这段代码,如果阻塞子等待输入,父级还在循环吗?
  • 没有。在您的原始代码中,父母和孩子都在等待对方完成编写,在我的代码中也是如此。如果您希望可以在一侧或两侧设置 I/O 非阻塞,只需在“一无所有”消息之后删除对 exit 的调用。它仍然可以工作,不需要信号量。他们有时会打印“一无所获”,有时会打印部分消息或几条消息,例如“rfoobarfoo”。但无论如何,您不应该依赖于通过一个read 调用来阅读整个消息。
  • 如果我只删除 exit,如果儿子正在等待输入,它不会授予我对父级的非阻塞行为,因为如果管道上没有任何内容可读取,则父级将等待直到它是。如果儿子没有数据,我需要那个父母仍在循环。
  • 当然你也需要为非阻塞输入添加fcntl
  • 然后,如果你想象我只删除了初始代码中的信号量,为什么如果儿子正确地写入管道,父母没有收到儿子的任何东西?
猜你喜欢
  • 1970-01-01
  • 2010-10-28
  • 1970-01-01
  • 2011-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多