这是一种无法实现的特殊场景。我想了解我“在做什么错误通过分支进程通过管道传递变量来执行Shell命令
情景:
1.叉一个子进程 2.子进程应执行shell命令(例如猫排序文件) 3。外壳命令的参数从父进程通过配管(用于G例如文件输入。猫排序)
我写以下程序但它显示的文件名,而不是打印出文件内容。但它挂着出到屏幕上
#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);
}
}
给予任何输出更新:
原来的例子是无效的。我更新了排序命令。
我想对内容进行排序。但屏幕挂,没有任何输出
这么傻,我忘了它。真的很糟糕的一天。我花了整整一天的时间去了解描述符关闭:)。非常感谢 – user3151330