2017-04-30 20 views
0

3つのexecv( "./ test"、execv_str)を並行して実行しようとしています。 execv()が正常に完了すると、成功メッセージを出力する必要があります。Cで並列にfork()とexec()を実行

しかし、今、私は次のようになります:

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

      } 
     } 
    } 
} 

ここでは何をしますか。フォークの後、私はpidを返し、それが0でないかどうかをチェックして(つまり、私たちは父のプロセスにいる)、父親が息子を待つようにします。 "成功"を表示するには、子プロセスが終了したときにトリガされるSIGCHLDシグナルをバインドします。 waitpidがジョブを完了した後、これはやや過剰なもので、printを置くことに注意してください。 (しかし、私はシグナルをバインドするのが好きです。)

+0

waitpid()を使用している場合は、引き続き並列実行を検討していますか? ps -auxをチェックすると、 grep ./testの場合、子プロセスは1つずつ生成され、同時に実行されません。 – ELIJAH

+0

確かに彼らは –

+0

ではありません出力の順序を制御したい場合、いくつかのプロセスを待たなければなりません –

関連する問題