这是我的问题:我的代码应该同时执行当前目录中的所有可执行文件(即所有二进制文件和所有脚本)。这是代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <dirent.h>
/* struct created for passing arguments at every thread */
struct thread_data {
long thread_id;
char *nome_file;
};
/* task of every thread */
void *work(void *thread_args) {
long tid;
char *name;
struct thread_data *my_data;
my_data = (struct thread_data *)thread_args;
tid = my_data -> thread_id;
name = my_data -> nome_file;
printf("thread number %ld get file %s\n", tid, name);
execl(name, name, (char *)0);
printf("execl failed\n");
pthread_exit(NULL);
}
int filter(const struct dirent *entry) {
/* Filter for scandir(): I consider only the regular files */
if(entry -> d_type == DT_REG)
return 1;
else
return 0;
}
int main() {
int n, rc;
long t;
struct dirent **namelist;
pthread_attr_t attr;
void *status;
/* Number of regular files in the current directory */
n = scandir(".", &namelist, filter, alphasort);
if(n < 0) {
perror("scandir()");
exit(EXIT_FAILURE);
}
/* How many threads? */
pthread_t thread[n];
/* Every thread will receive one instance of the struct thread_data */
struct thread_data thread_data_array[n];
/* With this, I'm sure my threads will be joinable */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(t=0; t<n; t++) {
printf("Main: creating thread %ld\n", t);
/* Filling the arguments in the struct */
thread_data_array[t].thread_id = t;
thread_data_array[t].nome_file = namelist[t] -> d_name;
rc = pthread_create(&thread[t], &attr, work, (void *)&thread_data_array[t]);
if(rc) {
printf("ERROR: pthread_create() is %d\n", rc);
exit(EXIT_FAILURE);
}
}
pthread_attr_destroy(&attr);
for(t=0; t<n; t++) {
rc = pthread_join(thread[t], &status);
if(rc) {
printf("ERROR: pthread_join() is %d\n", rc);
exit(EXIT_FAILURE);
}
printf("Main: join succeeded on thread %ld\n", t);
}
printf("Main: program finished. Quitting...\n");
pthread_exit(NULL);
}
我的程序成功读取了当前目录中的常规文件,每个线程每次获取一个文件,但是当执行第一个二进制文件或脚本时,程序退出!这是它的执行示例...
Main: creating thread 0
Main: creating thread 1
Main: creating thread 2
Main: creating thread 3
Main: creating thread 4
Main: creating thread 5
Main: creating thread 6
thread number 0 get file slide.pdf
execl failed
thread number 1 get file hello.sh
Congrats, you executed this script, I'm hello.sh!
然后,他不会继续执行其他文件。如果成功,错误可能在 execl 返回值中......