前叉,管道执行器和dub2 [英] fork, pipe exec and dub2
本文介绍了前叉,管道执行器和dub2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
该代码应该打印"ls -l'的输出:"并附加结果"ls -l",但不会... 有人知道这是怎么回事吗?
This code is supposed to print "Output from 'ls -l':" and append the result of 'ls -l', but it doesn't... Does anyone has a clue whats wrong with this?
#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);
}
}
推荐答案
在您的代码中,以下代码段中的sizeof(readbuffer)
等于4,因此它最多读取4个字节.
In your code the sizeof(readbuffer)
is equal to 4 in the following snippet., so it reads 4 bytes max.
void readStringFromFile (int file, char * readbuffer) {
int nbytes = read(file, readbuffer, sizeof(readbuffer));
readbuffer[nbytes] = 0;
}
您可以将缓冲区的大小作为另一个参数发送,给出:
You can send the size of the buffer as another parameter, giving:
void readStringFromFile (int file, char * readbuffer, int maxsize) {
int nbytes = read(file, readbuffer, maxsize);
readbuffer[nbytes] = 0;
}
并使用以下命令调用它:
and invoke it with:
readStringFromFile(fd[0], readbuffer, sizeof(readbuffer));
这篇关于前叉,管道执行器和dub2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文