我正在做一個小型的c程序來測試一些Unix命令。 我向用戶提供他可以測試的選項,然後允許他輸入他的選擇。如果用戶輸入數字2作爲他的選擇,則應該運行以下代碼來測試文件上的grep命令。但是當我輸入「模式」時,代碼 出現問題,它開始無限循環, 有什麼幫助?我在Unix編程方面沒有太多經驗。當我進入2號是我的選擇 出現問題,意味着它的情況下,2號使用grep與execl,它啓動一個無限循環?
#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' – Omkant
@OlafDietsche,thi是我如何定義模式 char pattern [50]; –