Find the answer to your Linux question:
Results 1 to 2 of 2
the following code is ran in Linux PC: // appropriate header files included int a[1024]; void *f1(void *) { char b[1024]; int len; while(1) { printf("\n in F1 \n"); printf("\n ...
  1. #1
    Just Joined!
    Join Date
    Sep 2007
    Posts
    11

    safe termination in the middle of thread function?

    the following code is ran in Linux PC:

    // appropriate header files included

    int a[1024];

    void *f1(void *)
    {
    char b[1024];
    int len;

    while(1)
    {

    printf("\n in F1 \n");
    printf("\n enter a string \n");
    gets(b);
    len=strcpy(a,b);
    if(len<=0)
    return NULL;

    sleep(1);
    }
    return NULL;
    }

    void *f2(void *)
    {
    int len;

    while(1)
    {
    printf("\n in F2 \n");
    sleep(1);
    }
    return NULL;
    }

    int main()
    {
    pthread_t th1;
    pthread_t th2;

    pthread_create(&th1,NULL,f1,NULL);
    pthread_join(th1,NULL);
    pthread_create(&th2,NULL,f2,NULL); // line #30
    pthread_join(th2,NULL);

    return 0;
    }


    When the program is ran in linux PC, output is as follows:

    (gdb) run
    Starting program: /home/vg/v
    [Thread debugging using libthread_db enabled]
    [New Thread -1208936768 (LWP 29527)]

    in F1
    enter a string

    [Thread -1208936768 (LWP 29527) exited]

    Program received signal SIGSEGV, Segmentation fault.
    [Switching to Thread -1208789312 (LWP 29537)]
    0x48ee4517 in memset () from /lib/libc.so.6
    (gdb) bt
    #0 0x48ee4517 in memset () from /lib/libc.so.6
    #1 0x48fea7e7 in pthread_create@@GLIBC_2.1 () from /lib/libpthread.so.0
    #2 0x08048738 in main () at b_vg.c:30

    When the user does not enter any string, string "b" has zero length. strcpy() returns zero to "len" var. So the following if condition is true and returns NULL to main(). Then segmentation fault is occuring in main() at the creation of 2nd thread i.e. at the line #30. I think this is due to returning in the middle from 1st thread function. Is there a safe way to return, in the middle of the thread function?

  2. #2
    Linux User
    Join Date
    Jul 2004
    Location
    Poland
    Posts
    368
    I doesn't have seem to have anything in common with the way you return from the function.
    My observations are as follows:
    1) strcpy doesn't return the length of the string as you assume, it returns pointer to destination string (a in you case).
    2) try compiling and linking with the -pthread flag.
    3) functions gets can override the buffer that is passed to it, in you case it seem unlikely but who knows, try using fgets instead.
    "I don't know what I'm running from
    And I don't know where I'm running to
    There's something deep and strange inside of me I see"

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...