【问题标题】:Using grep with execl ,it starts an infinite loop?使用 grep 和 execl 会启动无限循环吗?
【发布时间】:2012-11-13 07:23:39
【问题描述】:

我正在编写一个小型 c 程序来测试一些 Unix 命令。 我为用户提供他可以测试的选项,然后允许他输入他的选项。如果用户输入数字 2 作为他的选择,则应运行以下代码,该代码正在测试文件上的 grep 命令。但是代码有问题 当我进入“模式”时,它开始一个无限循环, 有什么帮助吗?!!我在 Unix 编程方面没有太多经验。 当我输入数字 2 作为我的选择时出现问题,这意味着它是在 case no.2

  #include <unistd.h>
  #include <sys/types.h>
  #include <errno.h>
  #include <stdio.h>
  #include <sys/wait.h>
  #include <stdlib.h>

    int main(){
    char pattern[50];
    int userInput;
    pid_t childPID; 
        char filename[50];   
    FILE *file;      

    printf("Enter a File name:");    
    scanf("%s",filename);    

        file = fopen(filename, "r");


do{
    printf("Enter what u want to do with the file:\n");
    printf("1.Compress the file.\n");
    printf("2.Search for a pattern at the file\n");
    printf("3.Read the file (display the file content at the terminal)\n");
    printf("4.Eject the program\n");

        scanf("%d",&userInput);
switch(userInput){
    case 1: 
        if(childPID == 0){
            execl("/bin/gzip","gzip",filename,NULL);

            exit(1);
            }       
        break;
    case 2: childPID = fork();
        if(childPID ==0){
            printf("Enter the pattern you want to search about:");
            scanf("%s",pattern);


            execl("/bin/grep","grep",pattern,filename,NULL);
        }   
        break;

    }

}while(userInput != 4);
return 0;
  }

【问题讨论】:

  • 模式是如何定义的?它是否足以容纳您的示例模式字符串?
  • 我认为你应该使用选项-f .. 表示将第四个参数传递为"-f" 然后filename
  • @OlafDietsche ,这就是我定义模式 char pattern[50];
  • @Omkant 我试过了,但是当我编译时,它产生了这个错误: Ass.c: In function 'main': Ass.c:45:39: error: 'f' undeclared (first在此函数中使用)Ass.c:45:39:注意:每个未声明的标识符对于它出现的每个函数只报告一次
  • 你怎么知道这是一个无限循环?究竟会发生什么?

标签: c ubuntu os.execl


【解决方案1】:

execlp()exec() 系列函数将当前进程映像替换为新进程映像,因此当 execlp() 退出时子进程终止,但 fork() 向父进程返回一些非零值。

重点是做了fork()之后有两个独立的进程

1st : main process called parent 
2nd : child process

而且你无法控制它们的执行顺序,它是未指定的。所以在子代码完成后将wait(NULL) 放入父代码中。

这样父母就会等到孩子终止。否则两个独立的进程都将以这种方式运行。有时您会发现只有父级在运行(that's infinite loop),但有时您会看到子级也在运行。

【讨论】:

  • 没错,它工作并停止了无限循环,非常感谢:)
【解决方案2】:

我看到这可能进入无限循环的唯一原因是execl() 失败。在execl() 之后打印 errno 以查看发生了什么问题。

...
    execl("/bin/grep","grep",pattern,filename,NULL);
    printf("errno=%d\n", errno);
}

break;

【讨论】:

  • 我不能停止执行程序知道错误是什么?!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-20
  • 2016-05-01
  • 2011-06-26
  • 1970-01-01
  • 2017-04-08
  • 2017-06-11
  • 2011-05-05
相关资源
最近更新 更多