Модераторы: Daevaorn
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> вопрос по pipe, Каналы ведут себя не так как ожидаю. 
V
    Опции темы
Jessy
Дата 17.5.2019, 20:01 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 12
Регистрация: 1.11.2010

Репутация: нет
Всего: нет



Вот код использования pipe который взят как пример и он работает. Одиночная отправка строки в канал и получение этой строки:

Код

import os
import sys
import time

_r, _w = os.pipe() 

processid = os.fork()
if processid:
    # This is the parent process 
    # Closes file descriptor w
    os.close(_w)
    r = os.fdopen(_r)
    print("Parent reading")

    str = r.read()
    print("text =", str)
    sys.exit(0)
else:
    # This is the child process
    os.close(_r)
    
    w = os.fdopen(_w, 'w')

    print("Child writing")
    w.write("Text written by child...")
    w.close()
    
    print("Child closing")
    sys.exit(0)


Если хочу слать сообщения по каналу в цикле, то ни одно не доходит. Вот так:

Код

import os
import sys
import time

_r, _w = os.pipe() 

processid = os.fork()
if processid:
    # This is the parent process 
    # Closes file descriptor w
    os.close(_w)
    r = os.fdopen(_r)
    print("Parent reading")
    while True:
        str = r.read()
        print("text =", str)
 
    sys.exit(0)
else:
    # This is the child process
    os.close(_r)
    
    w = os.fdopen(_w, 'w')
    while True:
        time.sleep(2)
        print("Child writing")
    
        w.write("Text written by child...")
        
    w.close()
    
    print("Child closing")
    sys.exit(0)


Буду признателен за подсказку в чем я туплю.
PM MAIL   Вверх
Jessy
Дата 17.5.2019, 23:06 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 12
Регистрация: 1.11.2010

Репутация: нет
Всего: нет



Не поленился на Си проверить, работает:

Код

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main(void)
{
        int     fd[2], nbytes;
        pid_t   childpid;
        char    string[] = "Hello, world!\n";
        char    readbuffer[80];

        pipe(fd);
        
        if((childpid = fork()) == -1)
        {
                perror("fork");
                exit(1);
        }

        if(childpid == 0)
        {
                /* Child process closes up input side of pipe */
                close(fd[0]);

                /* Send "string" through the output side of pipe */
                for (;;) {
                    write(fd[1], string, (strlen(string)+1));
                    sleep(1);
                }
                
                exit(0);
        }
        else
        {
                /* Parent process closes up output side of pipe */
                close(fd[1]);

                /* Read in a string from the pipe */
                for (;;) {
                    nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
                    printf("Received string: %s", readbuffer);
                }
        }
        
        return(0);
}


Чем для python такая конструкция особенная....
PM MAIL   Вверх
Jessy
Дата 17.5.2019, 23:38 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 12
Регистрация: 1.11.2010

Репутация: нет
Всего: нет



Вот так работает.

Код

import os
import sys
import time
_r, _w = os.pipe() 
processid = os.fork()
if processid:
    # This is the parent process 
    # Closes file descriptor w
    print("Parent reading")
    while True:
        str = os.read(_r, 50)
        print("text =", str)
 
    os.close(_r)
    sys.exit(0)
else:
    # This is the child process

    while True:
        time.sleep(2)
        print("Child writing")
    
        os.write(_w, b"Text written by child...")
        
    os.close(_w)
    
    print("Child closing")
    sys.exit(0)
    


Спасибо мишка.
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Python: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.1039 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.