首页 文章

Unix - 管道,分支,execlp,dup2,c程序

提问于
浏览
-2

这是一项任务 . 我是unix编程的新手,可以使用一些帮助 . 我需要创建一个执行以下操作的C程序:

In the main() function, it creates a pipe using the pipe() function, then creates two child processes with fork(). Child 1 redirects stdout to the write end of the pipe and then executes with execlp() the "ps -aux" command. Child 2 redirects its input from stdin to the read end of the pipe, then it executes the "sort -r -n -k 5" command. After creating both children, the parent process waits for them to terminate before it can exit. Note that you may have to create Child 2 first, followed by Child 1. The parent program does the same thing as a shell that runs the command "ps -aux | sort -r -n -k 5". You must use the fork(), pipe(), dup2(), close(), execlp() functions (or other exec() variation).

我是高年级的CS学生,对Windows编程非常精明,所以我不是要求解决方案,而是要求确切地说明需要做什么以及各种命令的含义 .

谢谢

1 回答

  • 0

    要做的事情:

    主要流程

    • 创建一个管道(参见: man pipe()

    • 启动2个子进程(参见: man fork

    • 等待它们退出(参见: man wait

    • 退出

    Chid 1

    • 重定向标准输出以写入管道末端(参见: man dup

    • 运行ps -aux(参见: man exec

    • 退出

    孩子2

    • 重定向读取管道末端到标准输入

    • 运行sort -r -n -k

    • 退出

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

    可能是最重要的事情 RTFM .

    这些函数的初始参数是要执行的文件的名称 . execl(),execlp()和execle()函数中的const char * arg和后续省略号可以被认为是arg0,arg1,...,argn . 它们一起描述了一个或多个指向以null结尾的字符串的指针的列表,这些字符串表示执行程序可用的参数列表 . 按照惯例,第一个参数应指向与正在执行的文件关联的文件名 . 参数列表必须由NULL指针终止,并且由于这些是可变参数函数,因此必须强制转换此指针(char *)NULL .

    特别是不要忘记最后一句话,并结束你的电话 execlp("ps", "ps", "-aux", NULL);NULL 的任何参数 .

相关问题