简体   繁体   English

execvp和fork无法正常工作

[英]execvp and fork not working as expected

I have the following code: 我有以下代码:

for (loop=0;loop<2;loop++) 
    {
        child_pid = fork();

        if (child_pid == 0)
        {
            rc = execvp ("/usr/local/some_program", arguments);
        }
    }

I change the arguments passed to /usr/local/some_program based on the value of loop. 我根据循环的值更改传递给/ usr / local / some_program的参数。 I want the some_program to parallel-ly execute two instances. 我希望some_program并行执行两个实例。 But i see that i first execute some_program once and only after it finishes that i get execute the second instance of some_program. 但是我看到我首先执行一次some_program,并且只有在完成后才执行some_program的第二个实例。

I not able to get them to run parallelly and independently. 我无法让它们并行和独立运行。

Instead of fork, should i use pthreads? 我应该使用pthreads而不是fork?

The some_program that i am trying to execute is completely unrelated to the parent process. 我尝试执行的some_program与父进程完全无关。

Thanks 谢谢

"I not able to get them to run parallelly and independently." “我无法让它们并行和独立运行。” - No. Both process will be executed in parallel. -否。这两个过程将并行执行。 To check that create two programs like this- 要检查以创建两个这样的程序,

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
   printf("Pid= %d\n", getpid());
   while(1);
}

Compile those 2 program's and make two executable files. 编译这两个程序并制作两个可执行文件。 Pass these 2 exe file names via command line arguments to main program and run that using system command.But your main program should be live. 通过命令行参数将这2个exe文件名传递给主程序,然后使用系统命令运行它。但是您的主程序应该是活动的。

for (loop=0;loop<2;loop++) 
{
    child_pid = fork();

    if (child_pid == 0)
    {
       system(argv[loop+1]);
       exit(0); // if you don't use exit your second exe file will be executed twice.
    }
}
while(1);

Now type ps command in terminal and find the TTY name and run the main program. 现在,在终端中键入ps命令并找到TTY名称并运行主程序。 Open a new terminal and type 打开一个新终端并输入

ps -e  | grep pts/X    // pts/X is main program running terminal name. it may pts/0 or pts/1 ...

Through this you can come to know that the two processes running parallelly or not. 通过此操作,您可以了解两个进程是否并行运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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