我正在尝试使用execvp运行grep命令。我必须将输出保存到output.txt这样的输出文件中。我试过的代码如下:
#include<iostream>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;
int main(){
pid_t pid = fork();
int status = 0;
char* args[] = {"grep", "-n", "out", "*", ">", "output.txt", NULL};
//char* args[] = {"out", "/os_lab/assign_01/*", "/usr", NULL};
if(pid == 0){
cout<<"I am Child Processn";
status = 2;
execvp("grep", args);
}
else if(pid > 0){
cout<<"I am Parent Processn";
wait(&status);
}
else{
cout<<"Error in system calln";
}
return 0;
}
当我运行这段代码时,终端上的输出如下所示:
I am Parent Process
I am Child Process
grep: *: No such file or directory
grep: >: No such file or directory
execvp()
函数直接调用程序并使用提供的参数执行程序。wildcards
和*
的使用是由shell终端提供的,因此grep
将*
理解为grep'ed
文件。
如果你想使用通配符和操作符>
调用grap,你应该在c++中使用system()
函数。
#include<iostream>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;
int main(){
pid_t pid = fork();
int status = 0;
//char* args[] = {"grep", "-n", "out", "*", ">", "output.txt", NULL};
//char* args[] = {"out", "/os_lab/assign_01/*", "/usr", NULL};
if(pid == 0){
cout<<"I am Child Processn";
status = 2;
//execvp("grep", args);
system("grep -n out * > output.txt");
}
else if(pid > 0){
cout<<"I am Parent Processn";
wait(&status);
}
else{
cout<<"Error in system calln";
}
return 0;
}