简体   繁体   English

执行读取

[英]Execlp with read

I wanna implement a program that reads from stdin using a shell command and then I have to store the input and do other things with it.我想实现一个使用 shell 命令从标准输入读取的程序,然后我必须存储输入并用它做其他事情。

        int a[2];
        if(pipe(a)==-1){
                err(1, "error while creating a pipe");
        }

        int fd=fork();
        if(fd<0){
                err(1, "error while forking");
        }

        if(fd==0){
                close(a[0]);
                dup2(a[1], 1);
                execlp("read", "read", NULL);
        }

        close(a[1]);
        dup2(a[0], 0);

It does not take an input, how I can fix it?它不需要输入,我该如何解决?

read is a shell built-in. read的是内置的 shell。 It can be run only as a shell command, not launched directly via any of the exec -family functions.它只能作为 shell 命令运行,不能通过任何exec -family 函数直接启动。 If you check, you will very likely find that your execlp() call is failing (returning a nonzero value), which is a twofold problem for you:如果您检查,您很可能会发现您的execlp()调用失败(返回非零值),这对您来说是一个双重问题:

  1. The failure itself means that the work you wanted done does not, in fact, get done.失败本身意味着你想做的工作实际上并没有完成。 But also但是也

  2. After execlp() returns, which it does only if it fails, the child process goes on to perform work that was intended only for the parent process.execlp()返回之后,它只有在失败时才会这样做,子进程继续执行仅适用于父进程的工作。

You should always check your system calls for errors, but more so for the exec -family functions than for most.你应该经常检查你的系统调用是否有错误,但对于exec -family 函数来说比大多数函数更重要。 Generally speaking, if execlp or one of its siblings fails, you want that process to perform an _exit(1) soon after.一般来说,如果execlp或其同级之一失败,您希望该进程在不久之后执行_exit(1)

The correct way to run a shell command via execlp is to launch a shell, specifying the command(s) to run via a -c argument.通过execlp运行 shell 命令的正确方法是启动 shell,通过-c参数指定要运行的命令。 That would look something like this:看起来像这样:

    execlp("/bin/sh", "sh", "-c", "read", (char *) NULL);

You can use a different shell ( bash , zsh , etc .) if you prefer.如果您愿意,可以使用不同的 shell ( bashzsh)。

But also , read consumes input and stores it in one or more shell variables.而且read消耗输入并将其存储在一个或多个 shell 变量中。 It does not produce output, so I'm not sure how you expect to determine whether it read anything or not.它不会产生 output,所以我不确定您希望如何确定它是否读取任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM