pthread and recursively calling execvp in C

Posted by eduke on Stack Overflow See other posts from Stack Overflow or by eduke
Published on 2011-11-12T17:21:51Z Indexed on 2011/11/12 17:51 UTC
Read the original article Hit count: 259

Filed under:
|
|
|
|

To begin I'm sorry for my english :)

I looking for a way to create a thread each time my program finds a directory, in order to call the program itself but with a new argv[2] argument (which is the current dir). I did it successfully with fork() but with pthread I've some difficulties. I don't know if I can do something like that :

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <dirent.h>


int main(int argc, char **argv) 
{

    pthread_t  threadID[10] = {0};
    DIR * dir;
    struct dirent * entry;
    struct stat status;
    pthread_attr_t attr;
pthread_attr_init(&attr);

int i = 0;
char *res;
char *tmp; 
char *file;

 if(argc != 3)
{
    printf("Usage : %s <file> <dir>\n", argv[0]);
    exit(EXIT_FAILURE);
}


 if(stat(argv[2],&status) == 0)
 {
    dir = opendir(argv[2]);
    file = argv[1];
 }
 else
    exit(EXIT_FAILURE);

while ((entry = readdir(dir))) 
{

  if (strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
{

  tmp = malloc(strlen(argv[2]) + strlen(entry->d_name) + 2);

  strcpy(tmp, argv[2]);
  strcat(tmp, "/");
      strcat(tmp, entry->d_name);
  stat(tmp, &status);

  if (S_ISDIR(status.st_mode))
  {     

    argv[2] = tmp; 
    pthread_create( &threadID[i], &attr, execvp(argv[0], argv), NULL);

    printf("New thread created : %d", i);
    i++;

   }
   else if (!strcmp(entry->d_name, file))
   {
        printf(" %s was found - Thread number = %d\n",tmp, i);
        break;
    }

    free(tmp);
}  



}

pthread_join( threadID[i] , &res );

exit(EXIT_SUCCESS);


}

Actually it doesn't works : pthread_create( &threadID[i], &attr, execvp(argv[0], argv), NULL);

I have no runtime error, but when the file to find is in another directory, the thread is not created and so execvp(argv[0], argv) is not called...

Thank you for you help,

Simon

© Stack Overflow or respective owner

Related posts about c

    Related posts about linux