You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言中通过管道给grep子进程传输入时出现用法错误的问题排查

问题:子进程调用grep持续输出用法提示

运行程序时反复收到grep的用法提示:

Usage: grep [OPTION] ... PATTERN [FILE] ...
Try 'grep --help' for more information.

相关代码(省略错误检查)

int main(int argc, char ** argv) {
    char *file = argv[1];
    char *str = argv[2];
    FILE *fp = fopen(file, "r");
    int grep_stat = 0;
    int pipe_grep[2];
    char word[50];
    pipe(pipe_grep);
    //fork grep process
    if (fork() == 0) {
        //GREP CHILD
        dup2(pipe_grep[0],STDIN_FILENO); //now at std in,0
        close(pipe_grep[1]); //close unused end of pipe
        close(pipe_grep[0]); //shared descriptor now closed
        //parent will pass file contents from pipe to search for string. 
        //should check input from stdin, the pipe
        char *args[] = {"grep", str,NULL};
        //grep_stat =
        execvp("grep", args);
    }
    else {
        //PARENT PROCESS
        close(pipe_grep[0]); //close unused side of pipe
        while (fgets(word,50,fp) != NULL) {
            write(pipe_grep[1], word, strlen(word));
            }

尝试过的调整

曾修改子进程中管道的关闭与重定向顺序:

if(fork()==0){
    close(pipe_grep[1]); //close unused end of pipe
    close(0); //close stdin
    dup(pipe_grep[0]); //takes lowest available descriptor, 0
    close(pipe_grep[0]); //close shared descriptor
    
}

问题根源

最初怀疑是管道或execvp的使用问题,但最终确认是运行程序时未传入全部所需参数:代码中需要通过命令行传入目标文件(argv[1])和搜索字符串(argv[2]),如果缺少这两个参数,str会为NULL,导致execvp传递给grep的参数不完整,触发grep的用法提示。

内容的提问来源于stack exchange,提问作者Gillian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 03:23:22