首页 > 解决方案 > 如何将 execv 用于 grep?

问题描述

我的 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

标签: cunixprocesssystem-callsexecv

解决方案


根据Linux 手册execv()

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 );

推荐阅读