Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

c - segmentation fault filing sleep function

hi every one i am getting a problem. i am using a sleep function. i have file which i open after 5 sec read all data and display it. it run for few time the give segmentation fault i am not getting it why its happening.i think there is nothing wrong with the file of program other wise it must hot have run thanks kindly help me
here is the code

#include<stdio.h>
#include <sys/stat.h>
#include<time.h>
#include<string.h>
void retrive()
{
FILE *fs;
char ch;
const int size =26;
const int size1 =3;
const int size2 =6;
        char sourceip[size];char destip[size];char sourceport[size2];char destport[size2];
        char sessionstart[size];char sessionend[size];char payload[size2];char sessionnum[size2]; 
  while(-1)
{      
    fs = fopen ( "processpacketlib.txt","r" ) ;
        if ( fs == NULL )
        {
               puts ( "Cannot open source file" ) ;
               return 0;
        }
int j;
int cnt =0;
printf("no of entries %d" , (noofentries("processpacketlib.txt")+1)/3);

//while(cnt<(noofentries("processpacketlib.txt")/3))
for(j=0;j<10;j++)
///ch= fgetc(fs);
//while(ch!=EOF)
{
int i=0;
printf("j = %d" ,j);
ch= fgetc(fs);
sourceip[i]=ch;
i++;
while ( ch!='	')
        {

ch = fgetc ( fs ) ;        
sourceip[i]=ch;
        i++;
         }
sourceip[--i]='';
 i=0;
//================================================

ch = fgetc ( fs ) ;
destip[i]=ch;
i++;
while ( ch!='	' )
        {

        ch = fgetc ( fs ) ;
        destip[i]=ch;

i++;
         }

destip[--i]='';
i=0;
//=================================================

ch = fgetc ( fs ) ;
sourceport[i]=ch;
//printf("eh %c",eh[0])   ;
i++;
while (ch!='	')
{
ch = fgetc ( fs ) ;
sourceport[i]=ch;
//printf("eh %c",eh[1])   ;
i++;
 }
sourceport[--i]='';
i=0;
//=================================================

ch = fgetc ( fs ) ;
destport[i]=ch;
//printf("np %c",np[0])   ;
i++;
while (ch!='	')
{
ch = fgetc ( fs ) ;
destport[i]=ch;
//printf("np %c",np[1])   ;
i++;
 }
destport[--i]='';
i=0;
//===============================================

ch = fgetc ( fs ) ;
payload[i]=ch;
//printf("np %c",np[0])   ;
i++;
while (ch!='	')
{
ch = fgetc ( fs ) ;
payload[i]=ch;
//printf("np %c",np[1])   ;
i++;
 }
payload[--i]='';
i=0;

//==================================================

//==================================================

ch = fgetc ( fs ) ;
sessionnum[i]=ch;
//printf("np %c",np[0])   ;
i++;
while (ch!='	')
{
ch = fgetc ( fs ) ;
sessionnum[i]=ch;
//printf("np %c",np[1])   ;
i++;
 }
sessionnum[--i]='';
i=0;


//=================================================
ch = fgetc ( fs ) ;
sessionstart[i]=ch;
//printf("np %c",np[0])   ;
i++;
while (ch!='
')
{
ch = fgetc ( fs ) ;
sessionstart[i]=ch;
//printf("np %c",np[1])   ;
i++;
 }
sessionstart[--i]='';
i=0;
//======================================================

ch = fgetc ( fs ) ;
sessionend[i]=ch;
//printf("np %c",np[0])   ;
i++;
while (ch!='
')
{
ch = fgetc ( fs ) ;
sessionend[i]=ch;
//printf("np %c",np[1])   ;
i++;
 }
sessionend[--i]='';

ch = fgetc ( fs ) ;
//----------------------------------------------------*/
csvwrite(sourceip,destip,sourceport,destport,sessionstart,sessionend,payload,sessionnum);

printf("
sip %s" , sourceip);
printf("
 dip %s" , destip);
printf("
source  %s",sourceport);
printf("
dest %s",destport);
printf("
t pay  %s",payload);
printf("
t hdr %s",sessionnum);
printf("
session strat %s",sessionstart);
printf("
session end %s",sessionend);

printf("
");

cnt++;
}// while ends
fclose(fs);
sleep(1);
}// outer infinite while ends

}
//==================================================================================

void csvwrite(char sourceip[],char destip[],char sourceport[],char destport[],char sessionstart[],char sessionend[],char payload[],char sessionnum[])
 {int retvalue;
int pos=0;
   char snum[5];char sstime[20];char payload1[10000] ;
struct tm tm;
time_t t;
char s[25]="Sat Feb 19 12:53:39 2011";
if (strptime(sessionstart, "%A %b %d %H:%M:%S %Y", &tm) != NULL)
tm.tm_isdst = -1;      
t = mktime(&tm);
//if (t != -1)
//printf("seconds since the Epoch: %ld
", (long) t);
char filename[35];
sprintf(filename,"%s%s%s%s",sourceip,"_",destip,".csv");
printf("filename %s",filename);

   FILE *fe = fopen(filename,"a");

   struct stat st;
   stat(filename, &st);
   int fsize = st.st_size;
   printf("before file size %d


" ,fsize);        
if(fsize==0)
 {
        char stringtime[15];
    fprintf(fe,"%s",sessionnum);
    fprintf(fe,"%s"," ");
        sprintf(stringtime,"%ld",(long)t);
    fprintf(fe,"%s",stringtime);
    fprintf(fe,"%s"," ");
    fprintf(fe,"%s",payload);
    fprintf(fe,"%s","
");
        fclose(fe);
        struct stat st1;
        stat(filename, &st1);
        int fsize1 = st1.st_size; 
        printf("after file size %d


" ,fsize1);
   }
//fclose(filenname);
else
 {
    int count =noofentries(filename);
    printf("count%d",count);
    int i=0;
    int k=0;
int len =0;

    FILE *f1 = fopen(filename,"r");
    //char snum[5];char sstime[20];char payload1[100000] ; int payloadentries=0;// change pasted below
while(k<count)
     {char snum[5];char sstime[20];char payload1[100000] ; int payloadentries=0;

          char ch;
      ch= fgetc(f1);
      pos++;
          len++;
          // printf("
ch = %c" ,ch);
          snum[i]=ch;
          i++;
        while (ch!=' ')
                {
                    ch = fgetc ( f1 ) ;
                pos++;
                len++;
                    snum[i]=ch;
                    //  printf("ch %c",ch)   ;
                    i++;
            }
                snum[--i]='';
                i=0;
//--------------------------------------------
                ch= fgetc(f1);
                pos++;
                len++;
                    // printf("
ch = %c" ,ch);
                    sstime[i]=ch;
                                i++;
              while (ch!=' ')
                     {
                    ch = fgetc ( f1 ) ;
                pos++;
                len++;
                    sstime[i]=ch;
                    //  printf("ch %c",ch)   ;
                                i++;
                    }
                    sstime[--i]='';
                    i=0;
//---------------------------------------------
                    ch= fgetc(f1);
                pos++;
                len++;
                    // printf("
ch = %c" ,ch);
                payload1[i]=ch;
                    i++;
         while (ch!='
')
                   {
                    ch = fgetc ( f1) ;
                pos++;
                len++;
                    payload1[i]=ch;
                    //  printf("ch %c",ch)   ;
                    i++;
                if(ch==' ')
                      {
                     payloadentries++;
                                      }

                  }
                payload1[--i]='';
                i=0;
                printf("
snum %s" ,snum);

                printf("
sstime %s" ,sstime);

                printf("
payload %s" ,payload1);

//  retvalue=addpayload(sourceip,destip,sourceport,destport,t,payload,sessionnum,snum,sstime,payload1,payloadentries+1,pos,count,filename);
//printf("rettttttttttvalue %d" ,retvalue);
        if ((retvalue==-2)||(retvalue==-1))
        {
printf("

BREAK

 ");
         break;
        }
           k++;

   }//while end
           fclose(f1);
 } //else end
}// function end
//====================================================================================
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The else branch of the if(fsize==0) conditional in csvwrite() does not fclose(fe). There is a limit on the number of files that can be opened by any one process at once; if you call this enough times, you'll hit the limit, and the next fopen() will return NULL (and errno will be set to EMFILE - "Too many open files").

That may or may not be the problem, so here's some more general advice:

  1. Use a debugger. If you don't know how, you should learn! For example:

    $ cat test.c
    #include <stdio.h>
    
    int main(void)
    {
        int a = 123, b, c;
        int *p = &a;
        int *q = NULL;
    
        b = *p;
        c = *q;
        printf("%d %d
    ", b, c);
        return 0;
    }
    $ gcc -Wall -o test test.c
    $ ./test
    Segmentation fault
    $
    

    Not very helpful. But compile with -g and run it with gdb:

    $ gcc -g -Wall -o test test.c
    $ gdb ./test
    GNU gdb 6.8-debian
    Copyright (C) 2008 Free Software Foundation, Inc.
    License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
    This is free software: you are free to change and redistribute it.
    There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
    and "show warranty" for details.
    This GDB was configured as "i486-linux-gnu"...
    (gdb) run
    Starting program: /tmp/test 
    
    ...and it will reveal the line where it fails:
    Program received signal SIGSEGV, Segmentation fault.
    0x080483d4 in main () at test.c:10
    10        c = *q;
    (gdb) quit
    The program is running.  Exit anyway? (y or n) y
    $ 
    
  2. Compile with warnings enabled (as I have done above with the -Wall flag). The compiler is capable of spotting quite a lot of silly things, but you have to ask it.

  3. Try indenting the code sensibly. Readable code is easier to debug.

  4. Remember to check return values. fopen() in particular can fail for any number of reasons which are unrelated to your program.

  5. Don't write vast amounts of practically identical code. If you have to do the same job more than once, consider factoring it out into a separate function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...