我想在 OpenMP 循环中运行可执行文件。 我试着用下面的代码来做到这一点:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main (int argc, char *argv[])
{
#pragma omp parallel
{
int thread_id = omp_get_thread_num();
char thread_name[4];
sprintf(thread_name, "%d", thread_id);
printf("%s\n", thread_name);
char* arg[] = {"task", thread_name, NULL};
execv("./task", arg);
}
}
可以像这样用gcc生成相应的可执行文件:
gcc -fopenmp hello.c -o hello
任务脚本是一个非常简单的 bash 脚本:
#! /bin/sh
echo "Hello, I am process $1"
echo 'Please for me for 10 seconds...'
sleep 10
echo 'Thank you!'
然后我这样运行我的程序:
./hello
来自包含“hello”可执行文件和“任务”脚本的目录。
3
2
0
1
Hello, I am process 3
Please for me for 10 seconds...
Thank you!
似乎当第一个线程(我的示例中的第 3 个线程)调用 execv 函数时,其他对 execv 的调用被跳过。
有人知道这里的问题是什么吗?
谢谢!
编辑:系统的新代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>
int main (int argc, char *argv[])
{
#pragma omp parallel
{
int thread_id = omp_get_thread_num();
char thread_name[4];
sprintf(thread_name, "%d", thread_id);
char command[50];
strcat(command, "./task ");
strcat(command, thread_name);
system(command);
}
}
最佳答案
函数 execv
将用一个新的进程替换当前进程,该进程使用给定函数的参数创建。
要实现你想要的,你应该使用system
,或者fork
/execv
这对组合。
关于在 OpenMP 循环中调用 execv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36405895/