【发布时间】:2016-11-30 14:04:57
【问题描述】:
在 Ubuntu 16 上,我正在尝试编写一个执行管道、分叉和执行的程序:
- 程序将通过命令行参数接受文件名;
- 子进程将打开命名文件并执行
cat将内容传输到第二个子进程;和 - 第二个子进程将执行
grep以选择包含数字的行以转发到第三个子进程 - 第三个子进程打印接收到的行。
这是我的代码:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include <string.h>
#include <sys/types.h>
#include<sys/wait.h>
#include<fcntl.h>
#define BLOCK_SIZE 4096
int main(int argc, char** argv)
{
int PID;
int pipe1[2];
int pipe2[2];
int pipe3[2];
char fileName[256];
int lengthfileName = strlen(argv[1]);
char content[BLOCK_SIZE];
char modifiedContent[BLOCK_SIZE];
int file;
if(argc < 2)
{
printf("Usage prog file\n");
exit(1);
}
if(pipe(pipe1) < 0)
{
printf("Error at pipe\n");
exit(1);
}
if(pipe(pipe2) < 0)
{
printf("Error at pipe\n");
exit(1);
}
if(pipe(pipe3) < 0)
{
printf("Error at pipe\n");
exit(1);
}
if((PID = fork()) < 0)
{
printf("Error at process\n");
exit(1);
}
if(PID == 0) //first child
{
close(pipe1[1]);
read(pipe1[0],fileName,lengthfileName);
close(pipe1[0]);
close(pipe2[0]);
dup2(pipe2[1],1);
close(pipe2[1]);
execlp("/bin/cat","cat",fileName,NULL);
exit(0);
}
else // parent
{
close(pipe1[0]);
write(pipe1[1],argv[1],lengthfileName);
close(pipe1[1]);
int status;
if((PID = fork()) < 0)
{
printf("Error at process\n");
exit(1);
}
if(PID == 0) // child 2
{
close(pipe2[1]);
//read(pipe2[0],content,BLOCK_SIZE);
//dup2(pipe2[0],0);// ***********************MARKED LINE HERE *****************************************
close(pipe2[0]);
close(pipe3[0]);
dup2(pipe3[1],1);
close(pipe3[1]);
execlp("grep","grep","[0-9]",NULL);
exit(0);
}
if((PID = fork()) < 0)
{
printf("Error at process\n");
exit(1);
}
if(PID == 0) //cod fiu 2
{
close(pipe3[1]);
read(pipe3[0],modifiedContent,BLOCK_SIZE);
close(pipe3[0]);
printf("GOT FROM PIPE:%s",modifiedContent);
exit(0);
}
waitpid(PID, &status, 0);
}
return 0;
}
我的问题在子进程 2 代码中,我尝试使用管道作为 grep 的输入。如图所示,输入来自终端;如果我取消注释标记的行,则程序挂起,我必须手动终止它以使其停止。
我在子进程 2 中使用 pipe2 向 grep 提供数据的方式有什么问题?还是其他地方有问题?
【问题讨论】:
-
第一个孩子的一个主要问题是
numeFisier不包含null 终止 字符串。 -
如果代码是英文的会很有帮助:) @Someprogrammerdude Joachim 你真棒,等待你的回答
-
@Someprogrammerdude 我不明白为什么这是个问题,我只在孩子一号的 2 个功能中使用它并且文件打开没问题,我的意思是孩子一号将文件内容完美发送到孩子 2
-
@VinayShukla 对不起,我翻译了代码:)
-
如果一个字符串没有终止,你将有未定义的行为。它似乎起作用只是侥幸。它可能会在您最意想不到的时候停止工作。