0

Python を使用して C プログラムのユーザー インターフェイスを実装したいと考えています。しかし、通信が機能していないようです。これまでに行ったことは次のtest.cとおりです。

int main()
{
    int pipe_in[2], pipe_out[2];
    if (pipe(pipe_in) != 0 || pipe(pipe_out) != 0)
    {
        perror("pipe");
    return 1;
    }

    int _proc_handle = 0;
    if ((_proc_handle=fork()) == 0)
    {
        printf("Starting up Python interface...\n");
        dup2(pipe_in[0], STDIN_FILENO);
        dup2(pipe_out[1], STDOUT_FILENO);
        close(pipe_in[0]);
        close(pipe_out[1]);
        execlp("python", "python", "interface.py", (char*)NULL);
        perror("execlp");
        printf("Error executing Python.\n");
        exit(1);
    }

    _write_fd = pipe_in[1];
    _read_fd = pipe_out[0];

    sleep(1);
    char buffer[256];
    int n = read(_read_fd, buffer, 11);

    printf("n: %d\n", n);
    printf("buffer: `%s'\n", buffer);
    write(_write_fd, "from C\n", 5);

    return 0;
}

そしてinterface.py次のとおりです。

import sys
import time

time.sleep(0.1)
print >>sys.stdout, 'from python'
print >>sys.stderr, sys.stdin.readline()

これを実行すると、印刷されると思っていましたが、

Starting up Python interface...
n: 11
buffer: `from python'
from C

しかし、代わりに、単にハングアップし、

Starting up Python interface...
4

1 に答える 1

0

Python スクリプトに追加します。

sys.stdout.flush() # after printing to stdout
sys.stderr.flush() # after printing to stderr

(行バッファリングは tty デバイスのデフォルトですが、パイプのデフォルトではありません)。

将来的には、親プロセス (および/または子) のパイプで EOF を検出する必要があり、親のパイプの未使用の端も閉じる必要があります。編集:そして、子プロセスでパイプの他の未使用の端を閉じます。

/* This should be in parent as well */
close(pipe_in[0]);
close(pipe_out[1]);

/* This should be added to the child */
close(pipe_in[1]);
close(pipe_out[0]);
于 2013-01-24T19:35:43.953 に答える