2017-04-30 52 views
0

我试图并行运行三个execv(“./ test”,execv_str)。当每个execv()成功完成时,我需要打印出成功消息。fork()和exec()在C中并行运行

但现在我得到的结果如下:

[email protected]:~/Desktop/$./test -p 
SUCCESS 
SUCCESS 
SUCCESS 
[email protected]:~/Desktop/$ TESTING 
TESTING 
TESTING 

预期的结果将是:

[email protected]:~/Desktop/$./test -p 
TESTING 
SUCCESS 
TESTING 
SUCCESS 
TESTING 
SUCCESS 
[email protected]:~/Desktop/$ 

这里是代码。

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/wait.h> 

int fork_execv() 
{ 
    int status; 
    pid_t pid; 

    pid = fork(); 

    /* Handling Child Process */ 
    if(pid == 0){ 
     char* execv_str[] = {"./test", NULL}; 
     if (execv("./test",execv_str) < 0){ 
      status = -1; 
      perror("ERROR\n"); 
     } 
    } 

    /* Handling Child Process Failure */ 
    else if(pid < 0){ 
     status = -1; 
     perror("ERROR\n"); 
    } 

    return status; 
} 

int main(int argc, char *argv[]){ 
    if (argc == 1){ 
     sleep(5); 
     printf("TESTING\n"); 
    } 
    else{ 
     int i; 
     for(i = 0; i < 3; ++i){ 
      if (fork_execv() != -1){ 
       printf("SUCCESS\n"); 
      } 
     } 
    } 
} 

如何修改我的代码使其工作?

+0

C不支持多线程 –

+1

@DeepeshChoudhary - 这个问题不涉及线程。 (并且请注意C实际上支持线程。) –

+0

@ Oliver Charlesworth真的吗?请告诉我如何(或共享链接)。我很久以来就想在c中使用它。 –

回答

0
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/wait.h> 

int fork_execv() 
{ 
    int status; 
    pid_t pid; 

    pid = fork(); 

    /* Handeling Chile Process */ 
    if(pid == 0){ 
     char* execv_str[] = {"./test", NULL}; 
     if (execv("./test",execv_str) < 0){ 
      status = -1; 
      perror("ERROR\n"); 
     } 
    } 

    /* Handeling Chile Process Failure */ 
    else if(pid < 0){ 
     status = -1; 
     perror("ERROR\n"); 
    } 

    return pid; 
} 
void handler(int sig){ 
    printf("SUCCESS\n"); 
} 
int main(int argc, char *argv[]){ 

    if (argc == 1){ 
     sleep(5); 
     printf("TESTING\n"); 
    } 
    else{ 

     int i; 
     pid_t process_id; 
     for(i = 0; i < 3; ++i){ 
      if ((process_id = fork_execv()) != -1){ 
       if(process_id != 0){ 
       signal(SIGCHLD, handler); 
       waitpid(process_id, NULL, 0); 
       } 

      } 
     } 
    } 
} 

在这里,我会做什么。在fork之后,我返回pid,检查它是否不是0(所以我们在父进程中)并让父亲等待儿子。要打印“成功”,我绑定在子进程结束时触发的SIGCHLD信号。请注意,这是一个小小的矫枉过正,并在waitpid完成这项工作后进行打印。 (但我喜欢绑定信号。)

+0

如果使用waitpid(),是否还在考虑并行运行?因为当我检查ps -aux | grep ./test,子进程是一个接一个产生的,不能并行运行。 – ELIJAH

+0

事实上,他们不是 –

+0

事实是,如果你想控制输出顺序,你必须等待一些进程 –