我试图通过execl调用grep。在通过stdin分叉和管道indata到新进程之后我试试这个:
execl("/bin/grep","grep","PATH",0);
它有效。但是我希望能够使用
中的参数int main(int argc, char ** argv) {}
然后我尝试:
execl("/bin/grep","grep",argv,0);
通过在控制台中编写“./program PATH”来调用该程序,但它不起作用;退出状态256退出grep进程。我认为问题是参数的格式。 Argv是一个以null结尾的char *数组,也许grep调用不是那样的。
我也希望有多个单词作为参数;所以你可以调用“./program -z PATH”作为例子。如何解决?
整个代码:
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char ** argv) {
int childExitStatus=0,childPID=0;
int cpipe0[2];
if(-1==pipe(cpipe0)) {
printf("Pipe failed");
exit(1);
}
// Fork printenv
childPID=fork();
if(-1==childPID) {
printf("Fork failed");
exit(1);
}
else if (0==childPID) {
if (-1==dup2(cpipe0[1],1)) {
printf("Pipe failed");
exit(1);
}
close(cpipe0[0]);
execl("/usr/bin/printenv","printenv",0);
printf("Execl failed");
_exit(1);
}
close(cpipe0[1]); // Close pipe0 write end
wait(&childExitStatus);
printf("Printenv exited with status: %d\n",childExitStatus);
if(childExitStatus!=0) {exit(1);}
// Fork grep
childPID=fork();
if(-1==childPID) {
printf("Fork failed");
exit(1);
}
else if (0==childPID) {
close(cpipe0[1]);
if (-1==dup2(cpipe0[0],0)) {
printf("Pipe failed");
exit(1);
}
execl("/bin/grep","grep","PATH",0);
// change to: execl("/bin/grep","grep",argv,0);
printf("Execl failed");
_exit(1);
}
wait(&childExitStatus);
printf("Grep exited with status: %d\n",childExitStatus);
if(childExitStatus!=0) {
printf("No matching environmental variables in GREP for supplied parameters\n");
exit(1);
}
return 0;
}
答案 0 :(得分:3)
如果您要传递数组,则需要致电execv()
。数组中的第一项应该是程序名,最后一项必须是NULL,所以创建一个修改过的argv[]
:
else if (0==childPID) {
const char **myArgs = NULL;
int i;
close(cpipe0[1]);
if (-1==dup2(cpipe0[0],0)) {
printf("Pipe failed");
exit(1);
}
myArgs = calloc(argc + 1, sizeof(char *));
myArgs[0] = "grep";
for (i = 1; i < argc; ++i )
myArgs[i] = argv[i];
myArgs[argc] = NULL;
execv("/bin/grep", myArgs);
printf("Execv failed");
_exit(1);
}