4

我对linux很陌生,所以。我无法让我的脚本工作。我只是在猜测,程序在执行 tr 函数时会暂停。

#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main()
{

int pdesc[2];
pipe(pdesc);

int a = fork();

if (a == 0) // child
    {

    dup2(pdesc[1],1); // chaning std_out to pipes_out
    execlp("ls", "ls", "-l", "-a", NULL);

    }
else       //parent
    {
    wait();
    int file1 = open("file.txt", O_WRONLY|O_CREAT|O_TRUNC,0777);
    dup2(pdesc[0], 0); // chaning std_in to pipes_in
    dup2(file1, 1); // chaning std_out to file's stream
    execlp("tr", "tr", "a-z", "A-Z", NULL);
    }



return 0;
}
4

1 回答 1

6

经典错误,所以,好问题。

您需要关闭父级和子级中未使用的管道文件描述符。

从管道读取的进程(本身)有一个打开的管道写入端,因此管道永远不会完全关闭,因此它永远不会传递 EOF。

此外,wait(2)导致死锁,程序不包含<sys/wait.h>,并且调用wait(2)缺少必需的参数。因为 shell 会等待父进程而不是子进程完成,所以实际上,wait(2)在这里某个地方打个电话会很好。但是在当前的双进程设计中你没有地方放它,因为你在父级的execlp(2). 解决这个问题的一种方法是让父 fork() 再次,并让原始 PID 除了 wait(2) 在循环中执行任何操作,直到所有子进程完成。

这是一个工作版本,还要注意对输出文件模式的更改。

#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main()
{
int pdesc[2];

    pipe(pdesc);

    int a = fork();

    if (a == 0) { // child
        dup2(pdesc[1],1); // chaining std_out to pipes_out
        close(pdesc[1]);
        close(pdesc[0]);
        execlp("ls", "ls", "-l", "-a", NULL);
    } else {      //parent
        int file1 = open("file.txt", O_WRONLY|O_CREAT|O_TRUNC, 0644);
        dup2(pdesc[0], 0); // chaning std_in to pipes_in
        dup2(file1, 1); // chaning std_out to file's stream
        close(pdesc[0]);
        close(pdesc[1]);
        close(file1);
        execlp("tr", "tr", "a-z", "A-Z", NULL);
    }
    return 0;
}
于 2012-11-03T17:28:11.307 回答