繁体   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