通过线程调用system() [英] Call system() by thread

查看:99
本文介绍了通过线程调用system()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我需要同时执行不同的bash脚本.
所以我想知道是否可以通过线程执行它们?

运行脚本将像压力测试一样...


你能提供例子吗?

例如,我想同时运行以下脚本:
system("./test1");
system("./test2");
system("./test3");

这是正确的吗?

Hi,

I need to execute different bash scripts at the same time.
So I was wondering if it is OK to execute them by threads?

Running the scripts will act like stress testing...


Can you provide example?

Example, I want to run the following scripts at the same time:
system("./test1");
system("./test2");
system("./test3");

is this correct?

static void *runTest(void *arg)
{
    system((char*)arg);
    return NULL;
}

int main()
{
   while (i < 3)
   {
      pthread_create(&tId, NULL, &runTest, szCommand[i]);
   }
   return 0;
}



但是如何等待所有脚本运行,以使程序不会结束?

谢谢!

*我正在Linux上运行...



but how do I wait for all the scripts to run, so that the program will not end?

thanks!

*I am runnning in Linux btw...

推荐答案

在创建每个线程之前,您需要创建一个同步对象",让我们说一个互斥体".将其创建为封闭".

当每个线程完成其系统调用时,让其信号"该对象以指示完成.

让主程序执行第二个循环,在该循环中等待对象被信号化",以便直到所有3个线程都完成后才退出.

可能还有其他方法可以完成此操作,但是基本思想是您需要包括主线程(以防止退出)与执行系统"调用的各个线程之间的同步.

研究适当的调用并将对象作为参数传递给线程是学生的一项练习,同时他也在探索使用pthreads实现同步的其他方法.
Prior to creating each thread, you need to create a "synchonization object", let''s say a "mutex" for each thread. Create it "closed".

When each thread completes its system call, have it "signal" the object to indicate completion.

Have the main program do a second loop where it waits for the object to be "signaled" so that it does not exit until all 3 threads have completed.

There may be other ways to accomplish this but the basic idea is that you need to include synchronization between the main thread (to prevent exit) and the individual threads doing the "system" calls.

Researching the proper calls and passing the object as an argument to the thread is an exercise for the student as is discovering other ways to achieve synchronization using pthreads.


这篇关于通过线程调用system()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆