简体   繁体   中英

Call execv in OpenMP loop

I would like to run an executable in an OpenMP loop. I tried to do it with the following code:

#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); 

    }
}

The corresponding executable can be generated with gcc like this:

gcc -fopenmp hello.c -o hello

The task script is a very simple bash script:

#! /bin/sh

echo "Hello, I am process $1"
echo 'Please for me for 10 seconds...'
sleep 10
echo 'Thank you!'

And I run my program like this:

./hello

from a directory containing both "hello" executable and "task" script.

3

2

0

1

Hello, I am process 3

Please for me for 10 seconds...

Thank you!

It seems that when execv function is called by the first thread (the 3rd one in my example), other calls to execv are skipped.

Does someone know what the problem is here?

Thanks!

EDIT: new code with system

#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);
    }
}

The function execv will replace the current process with a new one created with the parameters given to the function.

To achieve what you want, you should use system , or maybe the couple fork / execv .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM