使用管道中的数据作为函数的参数

问题描述

我正在开发一个程序,它分叉两个子进程并执行 ls -F 然后将该输出用作 nl 的参数。

//fork child 1
pid1 = fork();
if (pid1 == 0) // child 1
{
    close(fd[0]);                        // close read end of the pipe
    dup2(fd[1],1);                      // child 1 redirects stdout to write to the pipe
    execlp("/bin/ls","ls","-F",NULL); // run ls -F
    close(fd[1]);                        // close write end of the pipe
}

//fork child 2
pid2 = fork();
if (pid2 == 0) // child 2
{
    close(fd[1]);                      // close write end of the pipe
    dup2(fd[0],0);                    // child 2 redirects stdin to read from the pipe
    execlp("/usr/bin/nl","nl",fd[0],NULL); // run nl
    close(fd[0]);                      // close read end of the pipe
}

当我测试 execlp("/bin/ls",NULL) 时,它按预期使用了我的第三个参数“-F”。但是 execlp("/usr/bin/nl",NULL) 似乎无法识别管道中的数据。这是我第一次使用 dup2 和 execlp。有人可以分析 dup2 和 execlp 在孩子 2 中实际上在做什么吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)