'fork'에 해당되는 글 2건

  1. 2012.02.22 fork를 이용해서 동시에 5개 프로세서 구동 1

반응형


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>

int nMyMainPid = -1;
int nChildPid1 = -1;
int nChildPid2 = -1;
int nChildPid3 = -1;
int nChildPid4 = -1;

void MainLoopExit(int n);
void MainLoop1();
void MainLoop2();
void MainLoop3();
void MainLoop4();
void MainLoop5();

int main(int argc, char *argv[])
{
    int nIdx;

    for ( nIdx = 1; nIdx < NSIG; nIdx++ ) {
        sigset (nIdx, MainLoopExit);
    }

    nMyMainPid = getpid();

    fprintf(stdout, "nMyMainPid[%d]\n", nMyMainPid);

    nChildPid1 = fork();
    if( nChildPid1 < 0 ) {  /** 실패 **/
        fprintf(stdout, "ERROR_FORK_FAIL nChildPid1 \n");
    }
    else if( nChildPid1 == 0 ) {  /** 자식 **/
        MainLoop1();
    }
    else {  /** 부모 **/
               
        nChildPid2 = fork();
        if( nChildPid2 < 0 ) {  /** 실패 **/
            fprintf(stdout, "ERROR_FORK_FAIL nChildPid2 \n");
        }
        else if( nChildPid2 == 0 ) {  /** 자식 **/
            MainLoop2();
        }
        else {  /** 부모 **/

            nChildPid3 = fork();
            if( nChildPid3 < 0 ) {  /** 실패 **/
                fprintf(stdout, "ERROR_FORK_FAIL nChildPid3 \n");
            }
            else if( nChildPid3 == 0 ) {  /** 자식 **/
                MainLoop3();
            }
            else {  /** 부모 **/

              nChildPid4 = fork();
              if( nChildPid4 < 0 ) {  /** 실패 **/
                fprintf(stdout, "ERROR_FORK_FAIL nChildPid4 \n");
              }
              else if( nChildPid4 == 0 ) {  /** 자식 **/
                MainLoop4();
              }
              else {  /** 부모 **/
                MainLoop5();
              }
 
            }

        }

    }

}


void MainLoopExit(int n)
{

    fprintf(stdout, "MainLoopExit\n");

    if ( nChildPid4 > 0 ) {
        kill( nChildPid4, SIGTERM );
    }

    if ( nChildPid3 > 0 ) {
        kill( nChildPid3, SIGTERM );
    }

    if ( nChildPid2 > 0 ) {
        kill( nChildPid2, SIGTERM );
    }

    if ( nChildPid1 > 0 ) {
        kill( nChildPid1, SIGTERM );
    }

    if ( nMyMainPid > 0 ) {
        kill( nMyMainPid, SIGTERM );
    }

    exit( 0 );

}


void MainLoop1()
{
    while(1){
      fprintf(stdout, "MainLoop1 %d\n", getpid());
      sleep(10);
    }
}

void MainLoop2()
{
    while(1){
      fprintf(stdout, "MainLoop2 %d\n", getpid());
      sleep(10);
    }
}

void MainLoop3()
{
    while(1){
      fprintf(stdout, "MainLoop3 %d\n", getpid());
      sleep(10);
    }}

void MainLoop4()
{
    while(1){
      fprintf(stdout, "MainLoop4 %d\n", getpid());
      sleep(10);
    }
}

void MainLoop5()
{
    while(1){
      fprintf(stdout, "MainLoop5 %d\n", getpid());
      sleep(10);
    }
}


 

반응형
Posted by 공간사랑
,