gpt4 book ai didi

c - Unix - Pipe、forks、execlp、dup2、c 程序

转载 作者:行者123 更新时间:2023-11-30 20:38:08 24 4
gpt4 key购买 nike

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

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

我是一名计算机科学高年级学生,对 Windows 编程非常精通,所以我并不是在寻求解决方案,只是要求翻译一下到底需要做什么以及各种命令的含义。

谢谢

最佳答案

要做的事情:

主要流程

  • 创建一个管道(请参阅:man pipeline())
  • 启动 2 个子进程(请参阅:man fork)
  • 等待它们都退出(请参阅:man wait)
  • 退出

child 1

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

子2

  • 将管道的读取端重定向到标准输入
  • 运行 sort -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

关于c - Unix - Pipe、forks、execlp、dup2、c 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30418099/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com