gpt4 book ai didi

c - 使用 grep 和 execl ,它会启动无限循环?

转载 作者:行者123 更新时间:2023-11-30 15:53:34 28 4
gpt4 key购买 nike

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

最佳答案

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

要点是在执行fork()之后有两个独立的进程

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

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

这样父进程将等待子进程终止。否则两个独立的进程都会以这种方式运行。有时您会发现只有父进程在运行(这是无限循环),但有时您会看到子进程也在运行。

关于c - 使用 grep 和 execl ,它会启动无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13554316/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com