【发布时间】:2017-06-12 01:45:10
【问题描述】:
这是一种无法实现的特殊场景。我想知道我犯了什么错误。
场景:
1. fork 一个子进程
2. 子进程执行shell命令(如cat排序文件)
3. shell 命令的参数通过管道从父进程传递(例如 g.cat 排序的文件输入)
我已经编写了下面的程序但是它显示的是文件名而不是打印出文件内容。但是它没有在屏幕上给出任何输出就挂起
#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);
}
}
更新:
原始示例无效。我已更新为排序命令。
我正在尝试对内容进行排序。但是屏幕一直挂着,没有任何输出
【问题讨论】: