首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用execv for grep?

如何使用execv for grep?
EN

Stack Overflow用户
提问于 2020-03-23 18:20:16
回答 2查看 518关注 0票数 0

我的grep位于/bin/usr/grep中。我的子进程可以运行,但它不执行execv命令。我在我的"ques29.c“文件中搜索"include”一词,如下所示:

代码语言:javascript
复制
#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;
}   

输出

代码语言:javascript
复制
Parent: Process ID 140735031147632 Exit status of the child was 0
EN

回答 2

Stack Overflow用户

发布于 2020-03-23 18:36:08

每个the execv() Linux man page

v- execv()、execvp()、execvpe()

char *const argv[]参数是一个指针数组,指向以null结尾的字符串,表示新程序可用的参数列表。按照惯例,第一个参数应该指向与正在执行的文件相关联的文件名。指针数组必须以空指针结束。

你需要改变

代码语言:javascript
复制
    char *argv[] = { "-n", "include", "ques29.c", "NULL" };
    execv("/usr/bin/grep", argv); 

代码语言:javascript
复制
    char *argv[] = { "/usr/bin/grep", "-n", "include", "ques29.c", NULL };
    execv(argv[0], argv); 

正如注释中所指出的,处理对exec*()的失败调用可能应该这样做:

代码语言:javascript
复制
    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 );
票数 3
EN

Stack Overflow用户

发布于 2020-03-23 18:32:43

该数组需要以NULL指针结束,但在您的代码中,最后一个元素是字符串文字"NULL",第一个参数必须是可执行文件的路径:

而不是这样:

代码语言:javascript
复制
char *argv[] = { "-n", "include", "ques29.c", "NULL" };

你想要这个:

代码语言:javascript
复制
char *argv[] = {"/usr/bin/grep", "-n", "include", "ques29.c", NULL };
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60811633

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档