微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决使用管道中的数据作为函数的参数

我正在开发一个程序,它分叉两个子进程并执行 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 举报,一经查实,本站将立刻删除。