我的grep位于/bin/usr/grep中。我的子进程可以运行,但它不执行execv命令。我在我的"ques29.c“文件中搜索"include”一词,如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
pid = fork();
if (pid < 0)
perror("Failed to fork.");
else if (pid == 0)
{
char *argv[] = { "-n", "include", "ques29.c", "NULL" };
execv("/usr/bin/grep", argv);
}
else
{
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status))
{
int exit_status = WEXITSTATUS(status);
printf("Parent: Process ID %ld Exit status of the child was %d\n", (long)getpid, exit_status);
}
}
return 0;
} 输出
Parent: Process ID 140735031147632 Exit status of the child was 0发布于 2020-03-23 18:36:08
每个the execv() Linux man page
v- execv()、execvp()、execvpe()
char *const argv[]参数是一个指针数组,指向以null结尾的字符串,表示新程序可用的参数列表。按照惯例,第一个参数应该指向与正在执行的文件相关联的文件名。指针数组必须以空指针结束。
你需要改变
char *argv[] = { "-n", "include", "ques29.c", "NULL" };
execv("/usr/bin/grep", argv); 至
char *argv[] = { "/usr/bin/grep", "-n", "include", "ques29.c", NULL };
execv(argv[0], argv); 正如注释中所指出的,处理对exec*()的失败调用可能应该这样做:
execv(argv[0], argv);
// no need to check the return value as
// a successful call won't return
perror( "execv()" );
// note that return and exit() can cause
// problems with more complex code
_exit( 255 );发布于 2020-03-23 18:32:43
该数组需要以NULL指针结束,但在您的代码中,最后一个元素是字符串文字"NULL",第一个参数必须是可执行文件的路径:
而不是这样:
char *argv[] = { "-n", "include", "ques29.c", "NULL" };你想要这个:
char *argv[] = {"/usr/bin/grep", "-n", "include", "ques29.c", NULL };https://stackoverflow.com/questions/60811633
复制相似问题