簡體   English   中英

是否可以從命令行寫入打開的 pipe(來自 C 程序)?

[英]Is it possible to write to an open pipe (from a C program) from the command line?

假設我有一個 C 程序,它創建了一個孩子 throught fork 父進程在子進程結束之前結束,並且由於 pipe 為空,子進程在read系統調用時被阻塞。

If the processus ID of the child is 1500 , and by using the shell command ls -l /proc/1500/fd I see that a pipe is open, is it possible to write to this pipe from the terminal using a shell command so that read系統調用解除阻塞並且子進程完成其執行?

去過也做過。

噓 答案:

cat whatever >> /proc/pid/fd/0

C 答案:

pid_t pid = whatever;
char buf[30];
sprintf(buf, "/proc/%d/fd/0", pid);
FILE *f = fopen(buf, "w");

但是您似乎有在子進程中打開 pipe 的寫入一半的問題。 你應該在你的fork()調用之后立即關閉它(見man 2 close ),這樣讀者不會卡住,但可以觀察到 pipe 的結尾。 啟動器通常看起來像這樣。

    int pipefd[2];
    pid_t pid;
    pipe(pipefd);

    if ((pid = fork()) == 0) {
        dup2(pipefd[0], 0);
        close(pipefd[0]);
        close(pipefd[1]);
        /* ... */
        /* usually this goes to exec but it doesn't have to */
        _exit(3);
    }
    close(pipefd[0]);
    if (pid < 0) {
        close(pipefd[1]);
        return ;
    }
    int pipefeed = pipefd[0];
    /* ... */
    /* I'm guessing in your case you don't wait() */

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM