这是一种无关紧要的特殊情景 . 我想知道我在做什么错 .
Scenario:
1.分叉子进程2.子进程应执行shell命令(例如cat对文件进行排序)3 . shell命令的参数通过管道从父进程传递(例如,g . cat sort的文件输入)
我写了下面的程序,但它显示的是文件名,而不是打印出文件内容 . 但它挂起时没有给屏幕输出任何信息
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(){
int pipefd[2];
pipe(pipefd);
//create a pipe before you fork a child process
pid_t cpid = fork();
if(cpid < 0){
perror("Fork");
}
else if(cpid == 0){
printf("This is child process\n");
close(pipefd[1]);
close(0);
dup2(pipefd[0],0);
execlp("sort", "sort", NULL);
exit(0);
}
else{
printf("This is parent process\n");
close(pipefd[0]);
char *sort_array[] = {"hello", "amigos", "gracias", "hola"};
for (int i=0; i<4; i++){
write(pipefd[1],sort_array[i],strlen(sort_array[i]));
write(pipefd[1], "\n",1);
}
int cstatus;
wait(&cstatus);
}
}
Update:
原始示例无效 . 我已经更新到sort命令 .
我正在尝试对内容进行排序 . 但屏幕悬挂没有任何输出
2 回答
当您使用
dup
时,您使用管道输入模拟子进程stdin
,因此当您执行sort
而没有任何参数时,它会从stdin
读取并读取直到它看到EOF,因此您必须写入管道然后关闭它 .您希望将其名称传递到管道的文件打开并写入输出的位置在哪里?