0

我的程序应该从文件中读取 unix 命令,执行它,将结果保存到文件中。如果我只是尝试从控制台运行它,则执行没有问题。但是,如果我将输入重定向到文件,它会由于某种原因继续读取。我想我可能没有正确检测到 EOF,但这种方法似乎以前有效。

我试过调试,结果真的很奇怪。或带有输入的文件的示例

echo blablabla
true
false

它的输入行将按顺序排列

echo blablabla
true
falseecho blablabla

好像它读取了标准输出?还是标准输入?但如果我只是从控制台提供输入,它就可以工作。

FILE* script;
script=freopen(argv[argc-1], "r", stdin);
if(script==0){
  printf( "Error 1\n" );
  return 1;
}
int c;

while((c=fgetc(stdin))){
    if(c==EOF || c==4 || c<0){
        c='\n';
        exitLoop=true;
    }
    if(c!='\n'){
        inLine[i]=c;
        inLine[i+1]=0; //shouldn't be needed, but just in case
        i++;
    }else{
        inLine[i]=0;
        printf("inLine: %s i:%d\n\n",inLine,i);
        sleep(1);
        int result= 0;
        result= fork();
        if(result<0){
           printf("Failed creation of a new process. Most likely not enough memory\n");
           return 1;
        }else if(result==0){
           short int ak=childFunction(inLine,logPath,searchPath);
           return ak;
        }else if(result>0){
           int status=0;
           int d=(int)waitpid(result,&status,0);
        }else
           return -1;
        }
        i=0;
        if(exitLoop==true)
        break;
    }
}

编辑:

int childFunction(char in[],char logPath[], char searchPath[]){
FILE *logFile= fopen( logPath, "a" );
if(logFile==NULL)
return 1;
char** argv;
int stringCount=1;
char* path;
int i=0,j=0;
for(i=0;in[i]!=0;i++){
    if(in[i]==' ' || in[i]=='\t'){
        in[i]=0;
        stringCount++;
    }
}
argv = malloc(sizeof(char*)*(stringCount+1));
i=0;
argv[0]=in;
j++;
while(j<stringCount){
    if(in[i]==0){
        argv[j]=in+i+1;
        j++;
    }
    i++;
}
argv[stringCount]=NULL;
int processId=fork();
if(processId<0){
    printf("Error while forking.\n");
    exit(1);
}else if(processId==0){
    return execv(in,argv);
}
int c=0;
waitpid(processId,&c,0);
c=errno;
fprintf(logFile,"%d: %s\n", c, in);
fclose(logFile);
free(argv);
if(c!=0)
return(1);
else
return(0);
}
4

2 回答 2

1

Your issue is that fgetc() returns an int, not char. Since you want to be able to read any char (i.e. any byte) fgetc() will return the unsigned char value that was entered. EOF is defined as being less than 0, so that it can be distinguished.

You need to define c as an int so that you can identify the EOF, otherwise it will overlap with some valid character's value and as you discovered may not be detectable at all (if char is unsigned).

于 2013-03-30T02:23:08.653 回答
0

Okay. No idea what caused the problem. I did manage to go around it however, by reading the length of file beforehand, and simply exiting the loop after x characters were read.

于 2013-03-30T13:03:57.920 回答