【发布时间】:2011-11-12 17:21:51
【问题描述】:
首先我很抱歉我的英语:)
我正在寻找一种方法来在我的程序每次找到目录时创建一个线程,以便调用程序本身但使用新的 argv[2] 参数(即当前目录)。我用 fork() 成功地做到了,但是用 pthread 我遇到了一些困难。我不知道我是否可以这样做:
#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);
}
实际上它不起作用: pthread_create(&threadID[i], &attr, execvp(argv[0], argv), NULL);
我没有运行时错误,但是当要查找的文件在另一个目录中时,未创建线程,因此未调用 execvp(argv[0], argv)...
感谢您的帮助,
西蒙
【问题讨论】:
-
您的 pthread_create() 行甚至不应该编译。即使这样做,它也不会在创建的线程中运行 execvp。
-
这样删除你的问题内容是不礼貌的,因为这篇文章不仅为你服务,也为以后通过搜索找到它的任何人服务。
-
如果您希望将此内容与您的帐户解除关联,请标记此帖子。请不要再回滚了,它可能对其他人有帮助。
标签: c linux pthreads posix system