fork,pipe exec和dub2

时间:2014-03-09 14:19:57

标签: c fork pipe dup

此代码应该打印“输出来自'ls -l':”并附加'ls -l'的结果,但它不会...... 有没有人知道这有什么问题?

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

void readStringFromFile (int file, char * readbuffer) {
    int nbytes = read(file, readbuffer, sizeof(readbuffer));
    readbuffer[nbytes] = 0;
}

int main(int argc, char const *argv[])
{
    int fd[2];
    pipe(fd);

    if (fork()==0)//child process
    {   
        close(fd[0]);
        dup2(fd[1],1);
        int retValue = execl("/bin/ls","ls","-l", NULL);
        printf("Exec failed: retValue = %d\n",retValue);
    } else
    {
        int status;
        close(fd[1]);
        wait(&status);
        char readbuffer[1024];
        readStringFromFile(fd[0],readbuffer);
        printf("Output from 'ls -l':\n %s", readbuffer);
    }
}

1 个答案:

答案 0 :(得分:2)

在您的代码中,sizeof(readbuffer)在以下代码段中等于4.,因此它最多读取4个字节。

void readStringFromFile (int file, char * readbuffer) {
   int nbytes = read(file, readbuffer, sizeof(readbuffer));
   readbuffer[nbytes] = 0;
}

您可以将缓冲区的大小作为另一个参数发送,给出:

void readStringFromFile (int file, char * readbuffer, int maxsize) {
   int nbytes = read(file, readbuffer, maxsize);
   readbuffer[nbytes] = 0;
}

并使用:

调用它
readStringFromFile(fd[0], readbuffer, sizeof(readbuffer));