【问题标题】:C -> Shell - Block on a Write Until ReadC -> Shell - 阻止写入直到读取
【发布时间】:2017-07-07 15:34:59
【问题描述】:

我想将一个字符从一个 c 程序发送到一个 shell 程序。我正在使用命名管道在需要时发送字母“a”。我应该只需要打开一次管道。这是一个例子:

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
int main(){
    int fd;
    mkfifo("/tmp/test", 0666);
    fd = open("/tmp/test", O_WRONLY);
    printf("Opened\n");
    char * a = "a";
    while(1){
            printf("Writing to pipe...\n");
            write(fd,a,1);
            sleep(1);
    }
}

shell 会根据需要多次执行此命令...

head -c 1 /tmp/test

问题是在一个头之后,即使没有人在那里,c 也会源源不断地流入管道。

我注意到 open() 会阻塞,直到有人在另一端。如何告诉 write() 在有人阅读之前阻止?

我宁愿在 write() 上使用此功能而不是 read(),因为我认为为每个请求打开文件会产生很多开销。

谢谢!

更新

这就是我在 Java 中处理它的方式,它会等到有人在这个管道上监听它才会继续。也许只是因为它是一种高级语言。

public static void writeToPipe(int val, String pipename){
    try{
        pipe_out = new PrintStream("/tmp/" + pipename);
    }catch(Exception e){
        System.out.println("Could not open a pipe for output!");
        e.printStackTrace();
    }
    try{
        pipe_out.println(val);
    }catch(Exception e){
        System.out.println("Could not write to pipe!");
        e.printStackTrace();
    }

    try{
        pipe_out.close();
    }catch(Exception e){
        System.out.println("Could not close the output pipe!");
        e.printStackTrace();
    }
}

更新 #2 - 这是解决方案

这是我根据 David 的想法编写的代码,它很粗糙,但它确实有效。我没有检查命名管道是否存在,只是阻止它退出。

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, char **argv){
    mkfifo("/tmp/test", 0666);
    while(1){
      int fd, status;
            if ((fd = open ("/tmp/test", O_WRONLY)) == -1) {
         perror ("open failed");
         return 1;
            }
     printf("Opened Pipe\n");
     char a = 'a';
            int f  = fork();
            if(f == -1){
                    perror("fork");
                    exit(1);
            }else if(f == 0){
                    //This is by the child process
                    if (write (fd, &a, 1) == -1) {
                            close(fd);
                    perror ("open failed");
                            return 1;
         }

            }else{
                    //This is the parent process
                    int w = waitpid(f, &status, WUNTRACED | WCONTINUED);
                    if (w == -1){
                            perror("waitpid");
                            exit(EXIT_FAILURE);
                    }
            }
    }
}

【问题讨论】:

  • 这可能是一个缓冲的东西。如果您向管道写入了足够多的数据,则写入将阻塞,直到有人开始从中读取(或者写入可能会返回 EAGAIN 或类似内容)。

标签: c shell


【解决方案1】:

你可以做你正在尝试的事情,但是你必须明白你必须在 shell 端将你的读取限制为 one-char,因为不会有'\n' 写入管道。此外,您可以write 比 shell reads 更多次。例如,您可以按照 Pursell 先生的建议添加验证,以确保您的 C 程序在write 上运行并阻塞,类似于:

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>

int main (int argc, char **argv) {

    int fd;
    errno = 0;

    if (mkfifo (argc > 1 ? argv[1] : "/tmp/test", 0666)) {
        perror ("mkfifo failed");
        return 1;
    }
    if ((fd = open ("/tmp/test", O_WRONLY)) == -1) {
        perror ("open failed");
        return 1;    
    }

    printf ("Opened\n");
    char a = 'a';

    while (1) {
        printf ("Writing to pipe...\n");
        if (write (fd, &a, 1) == -1) {
            perror ("open failed");
            return 1;
        }
    }

    return 0;
}

你可以用一个简单的测试:

$ declare -i c=0; while test "$c" -lt 10 && read -n 1 ch; do 
    echo "read: $ch"
    ((c++))
done </tmp/test

Shell 输出示例

read: a
read: a
read: a
read: a
read: a
read: a
read: a
read: a
read: a
read: a

您将write 直到fifo 缓冲区已满,导致Writing to pipe... 比您拥有的read: a 多。


fork 的粗略示例

继续这里的 cmets 是一个粗略的示例,它使用 fork 生成子进程以确保您的 C 程序始终在 shell 的写入时阻塞。此示例限制为 3 次重复,但您可以使用 while (1) 进行连续循环。我还为write 添加了一个快速计数器(只是出于我的好奇心),例如

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

int crt_fifo_write (char *fname);
int file_exists (char *f);

int main (int argc, char **argv) {

    int n = 0;
    errno = 0;

    while (n < 3) {         /* limit example to 3 child processes */

        pid_t cpid, w;
        int status;

        cpid = fork();
        if (cpid == -1) {
            perror("fork");
            exit(EXIT_FAILURE);
        }

        if (cpid == 0) {    /* Code executed by child */
            if (!crt_fifo_write (argc > 1 ? argv[1] : "/tmp/test"))
                fprintf (stderr, "crt_fifo_write() failed.\n");
        } 
        else {              /* Code executed by parent */
            do {
                w = waitpid (cpid, &status, WUNTRACED | WCONTINUED);
                if (w == -1) {
                    perror("waitpid");
                    exit(EXIT_FAILURE);
                }
                if (WIFSIGNALED(status)) /* signal on close of read end */
                    printf("shell read complete. %s\n", 
                            n < 2 ? "restarting" : "done");
            } while (!WIFEXITED(status) && !WIFSIGNALED(status));
        }
        n++;
    }

    return 0;
}

/** your write 'a' to the fifo with check for existence & unlink */
int crt_fifo_write (char *fname)
{
    int fd, n = 0;
    errno = 0;

    if (!fname || !*fname) return 0;

    if (file_exists (fname))
        if (unlink (fname) == -1) {
            perror ("fifo exists unlink failed");
            return 0;
        }

    if (mkfifo (fname, 0666)) {
        perror ("mkfifo failed");
        return 1;
    }
    if ((fd = open (fname, O_WRONLY)) == -1) {
        perror ("open failed");
        return 1;    
    }

    printf ("Opened\n");
    char a = 'a';

    while (write (fd, &a, 1) != -1) {
        printf ("%3d - Writing to pipe...\n", n++);
    }

    return 0;
}

/** atomic test that file exists (1 success, 0 otherwise) */
int file_exists (char *f)
{
    errno = 0;
    int flags = O_CREAT | O_WRONLY | O_EXCL;
    int mode = S_IRUSR | S_IWUSR;
    int fd = open (f, flags, mode);

    if (fd < 0 && errno == EEXIST)
        return 1;
    else if (fd) {  /* created, like bash touch */
        close (fd);
        unlink (f);
    }

    return 0;
}

示例程序使用/输出

$ ./bin/pipe_write_shell_fork
Opened
  0 - Writing to pipe...
  1 - Writing to pipe...
  2 - Writing to pipe...
  3 - Writing to pipe...
  4 - Writing to pipe...
    ...
138 - Writing to pipe...
139 - Writing to pipe...
140 - Writing to pipe...
shell read complete. restarting
Opened
  0 - Writing to pipe...
  1 - Writing to pipe...
  2 - Writing to pipe...
  3 - Writing to pipe...
  4 - Writing to pipe...
    ...
    130 - Writing to pipe...
131 - Writing to pipe...
shell read complete. restarting
Opened
  0 - Writing to pipe...
  1 - Writing to pipe...
  2 - Writing to pipe...
  3 - Writing to pipe...
  4 - Writing to pipe...
    ...
144 - Writing to pipe...
145 - Writing to pipe...
shell read complete. done

Shell 读取/输出示例

$ declare -i c=0; while test "$c" -lt 10 && read -n 8 ch; do \
echo "read: $ch"; ((c++)); done </tmp/test
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa

(再重复 2 次)

【讨论】:

  • 虽然这非常棒,但我仍然不确定如何在循环完成后保持代码继续运行。我想要它,这样我就可以重新执行你的 shell 循环,而不必重新启动 c 程序。
  • 这可能需要考虑管道本身的一些选项。 mkfifo 通常需要同时打开两个读/写端。当 shell 完成读取时,它有效地关闭了读取端,告诉你的 C 程序它是用 SIGPIPE 完成的,正如 William 所指出的那样。您必须在 C 程序中捕获和处理该信号,并且很可能需要删除并重新初始化 fifo。
  • 有趣的是,Java 似乎以不同的方式处理管道,可能是因为它是多平台的?我可以使用 java 将数据放入管道中,它会等到有人从输出管道中读取数据后再继续。
  • 您最好的选择是使用fork 来设置fifo 和write 的程序,如上所述。父进程可以在子进程上waitpid 终止,然后生成另一个子进程并重复。这样,子进程将在每个SIGPIPE 处终止,而父进程将在下一个 shell 进程启动读取时将其替换为等待写入的新进程。可能还有其他方法可以处理它,但这是我想到的第一个方法。
  • @Demodude123 man 2 wait 有一个可以在循环中使用的 fork/waitpid 框架的好例子。您将需要检查/tmp/test(或您使用的任何名称)是否存在,如果存在则将其删除,使用mkfifo 重新创建fifo 并设置write。一个新进程将在 shell 的读取端关闭时创建。 (本质上看起来就像你的 java 代码在做什么,它只是在处理幕后的细节)
【解决方案2】:

由于您不费心检查write 的返回,您甚至不会注意到它失败了。 (也就是说,它不是无休止地流入管道;它只是对你撒谎并打印“Writing to pipe...”而未能写入管道。)

阻止写入的唯一方法是填充管道。但这不是你的问题。问题是管道已终止。如果你想保持那个管道打开,你需要让一些仍然活着的进程从中读取。例如,您可以在其他 shell 中执行sleep 500 &lt; /tmp/test。或者只是在编写程序中打开fifo进行读取。 (例如,添加行open("/tmp/fifo", O_RDONLY);)

更奇怪的问题是;为什么您的程序没有从 SIGPIPE 终止?

【讨论】:

  • 好的,它“失败”如何帮助我编写一个解决方案来防止它轮询 write()?我可以睡着再试一次,但这违背了阻止的目的。
  • @Demodude123 编辑了更多细节和一些关于制作写入块的建议。
  • 这是个好主意,但其中任何一种方式都会导致 C 程序继续打印到管道。这不是应要求。解决这一切的草率方法是在循环中使用 open(),但我试图避免每次调用此 C 代码时都重新创建文件描述符。
  • 它只打印到管道缓冲区已满。如果您希望在某个消费者准备好之前不生成数据,那么管道是错误的 IPC 形式。但是,您可以更改管道缓冲区的大小以使其适合您的目的:stackoverflow.com/questions/4739348/…
  • 尝试在内核 2.6.32 上运行它,不支持,但是很棒的发现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多