我试图用C编写程序来搜索某个文件中的单词 你可以帮帮我吗?
#include<unistd.h>
#include<sys/types.h>
#include<stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>
int main()
{
int pid;
//string s;
//s = grep();
pid = fork();
if(pid < 0)
{
printf("Failed");
exit(-1);
}
else if ( pid == 0)
{
printf("Child id %d\n",getpid());
execlp("/bin/bzexe","grep the", NULL);
}
else
{
wait(NULL);
printf("Parent id %d |\n ",getpid());
exit(0);
}
return 0;
}
答案 0 :(得分:0)
当您调用execlp
时,该命令的参数必须是该函数的单独参数。所以它应该是:
execlp("/bin/bzexe", "grep", "the", (char*)NULL);
您还应该将NULL
参数转换为(char*)
,因为NULL
宏不必扩展为指针类型,而varargs函数如execlp
不要自动转换为指针类型。
答案 1 :(得分:0)
如果您尝试使用 exec() 系统调用在某个文件中搜索单词,那么您可以使用以下命令来完成:
execlp("bash", "bash", "-c", "grep word filename.extension", (char *) NULL);
例如,要在 q1.cpp 中搜索字母“a”,您可以使用以下命令:
execlp("bash", "bash", "-c", "grep a q1.cpp", (char *) NULL);
在“-c”的情况下,您可以在一个参数中运行多个命令。
如果你想用 execl() 完成同样的任务,那么你可以使用下面给出的命令来完成:
execl("/bin/sh", "sh", "-c", "grep word filename.extension", (char *) NULL);