Unix - 管道、叉子、execlp、dup2、c 程序

Unix - Pipe, forks, execlp, dup2, c program

这是作业。我是 unix 编程的新手,需要一些帮助。我需要创建一个执行以下操作的 C 程序:

在main()函数中,它使用pipe()函数创建了一个管道,然后使用fork()创建了两个子进程。 Child 1 将 stdout 重定向到管道的写入端,然后使用 execlp() 执行 "ps -aux" 命令。子节点 2 将其输入从标准输入重定向到管道的读取端,然后执行 "sort -r -n -k 5" 命令。 创建两个子进程后,父进程等待它们终止,然后才能退出。 请注意,您可能必须先创建 Child 2,然后再创建 Child 1。 父程序与运行命令 "ps -aux | sort -r -n -k 5" 的 shell 执行相同的操作。您必须使用 fork()、pipe()、dup2()、close()、execlp() 函数(或其他 exec() 变体)。

我是 CS 的高年级学生并且非常精通 windows 编程,所以我不是在寻求解决方案,只是关于究竟需要做什么以及各种命令的翻译均值。

谢谢

待办事项:

主进程

  • 创建管道(参见:man pipe()
  • 启动 2 child 个进程(参见:man fork
  • 等待他们两个都退出(参见:man wait
  • 退出

孩子 1

  • 重定向标准输出以写入管道末端(参见:man dup
  • 运行 ps -aux(参见:man exec
  • 退出

Child 2

  • 将管道的读取端重定向到标准输入
  • 运行 排序-r -n -k
  • 退出

关于execlp,您可以在手册页中找到相关信息。 (man exec)。最有趣的 pnrt 回答你下面引用的问题:

可能是要做的最重要的事情 RTFM.

The initial argument for these functions is the name of a file that is to be executed. The const char *arg and subsequent ellipses in the execl(), execlp(), and execle() functions can be thought of as arg0, arg1, ..., argn. Together they describe a list of one or more pointers to null-terminated strings that represent the argument list available to the executed program. The first argument, by convention, should point to the filename associated with the file being executed. The list of arguments must be terminated by a NULL pointer, and, since these are variadic functions, this pointer must be cast (char *) NULL.

尤其不要忘记最后一句话并结束你的调用参数 execlp("ps", "ps", "-aux", NULL); 或任何可能带有 NULL.

的参数