Unix shell 编程

发布于 2024-12-05 12:09:43 字数 147 浏览 0 评论 0原文

我需要帮助编写 shell。我目前正在创建管道并生成关联的子进程以读取和写入管道。似乎不起作用的部分是父进程和子进程之间的通信。我需要这方面的帮助。首先,如果您能解释一下这是如何工作的(以及标准输入和标准输出),并帮助我剖析我所需要的内容以帮助我理解我所缺少的内容,我将不胜感激。

I am in need of help writing a shell please. I am currently in the process of creating pipes and spawning associated child process to read and write to the pipe. The part that does not seem to work is communication between the parent and the child process. I need help with this please. First off, I would appreciate it if you would please explain how this would work (Stdin and Stdout as well) and also help me dissect what I have to help me understand what I am missing.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一杆小烟枪 2024-12-12 12:09:43

总体情况是:

  1. 您需要创建一个管道,例如使用 pipeline(2)。对管道的调用返回一个文件描述符,该描述符必须存储在变量中。
  2. 您调用 fork(2),它将复制当前进程,包括打开的文件和文件描述符。
  3. 两个进程都使用 dup2(2) 来重定向 stdin/out。例如, dup2(pipe, STDOUT) 将当前进程(但不是分叉进程!)的 stdout 重定向到管道中。
  4. 使用 execve(2) 等在您刚刚设置的环境中启动其他进程。

如果需要捕获子进程的输入、输出和错误,则需要三个管道和相应的 dup2 调用:

int in,out,err,child; 
in = pipe(); out = pipe(); err = pipe();
child = fork();
if ( child == 0 ) {
    dup2( in, STDIN );
    dup2( out, STDOUT );
    dup2( err, STDERR );
    execve(something);
} else {
    /* read from out and err and write into in as necessary. */
}

The general picture is:

  1. You need to create a pipe, e.g. with pipe(2). The call to pipe returns a file descriptor, which must be stored in a variable.
  2. You call fork(2), which will duplicate your current process including the open file and the file descriptor.
  3. Both processes use dup2(2) to redirect stdin/out. For example, dup2(pipe, STDOUT) redirects stdout of the current process (but not the forked one!) into the pipe.
  4. Use execve(2) and friends to start other processes in the environment you set just up.

If you need to capture input, output and error from a child process, you need three pipes and according dup2 calls:

int in,out,err,child; 
in = pipe(); out = pipe(); err = pipe();
child = fork();
if ( child == 0 ) {
    dup2( in, STDIN );
    dup2( out, STDOUT );
    dup2( err, STDERR );
    execve(something);
} else {
    /* read from out and err and write into in as necessary. */
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文