简体   繁体   English

我的Linux下的C程序出了什么问题:“ ls -al | tr az AZ> file.txt”?

[英]What's wrong with my under-linux c prog: “ls -al | tr a-z A-Z > file.txt”?

I'm very new with linux and so. 我对linux还是很陌生。 I can't get my script working. 我的脚本无法正常工作。 I'm just guessing, that the program is getting suspended at executing tr function. 我只是在猜测,该程序在执行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;
}

Classic mistake, so, good question. 经典错误,所以,很好的问题。

You need to close the unused pipe file descriptors in both the parent and the child. 您需要关闭父级和子级中未使用的管道文件描述符。

The process reading from the pipe has (itself) an open pipe write end, so the pipe never gets completely closed, so it never delivers an EOF. 从管道读取的过程(本身)具有开放的管道写端,因此管道永远不会完全关闭,因此永远不会传递EOF。

Also, the wait(2) is causing a deadlock, the program doesn't include <sys/wait.h> , and the call to wait(2) is missing a required argument. 另外, wait(2)导致死锁,程序不包含<sys/wait.h> ,并且对wait(2)的调用缺少必需的参数。 Because the shell will wait for the parent to finish but not the child, it would be nice, actually, to have a wait(2) call in here somewhere. 因为外壳程序将等待父级而不是子级完成,所以实际上在这里的某个地方调用wait(2)会很好。 But in the current two-process design you have no place to put it, because you aren't in control after the parent's execlp(2) . 但是在当前的两进程设计中,您无处可放,因为在父级的execlp(2)之后您不受控制。 One way to fix that would be to have the parent fork() again, and have the original PID do nothing except wait(2) in a loop until all children have finished. 解决该问题的一种方法是再次使父fork()循环,并让原始PID在循环中除了wait(2)之外什么都不做,直到所有子项都完成为止。

Here is a working version, note also the change to the output file mode. 这是一个工作版本,还请注意对输出文件模式的更改。

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM