반응형

연구실에서 MultiProcessor로 구성되어있는 Processor를 Full로 돌려서,  사용할 일이 있는데
처음에는 Bash shell의 &를 통한, 간단한 구현으로 여러 Process를 돌렸다. 하지만
시간이 약간씩 Loss가 되는(여러작업을 Continuous하게 돌리기 때문에) 일이 발생하였다.
그래서
fork()함수와 execl()함수를 이용한, 여러 Process를 Countinous하게 구동하는 예제를 작성하였다.

TOTAL_PS 는 전체 Process의 개수
NUM_PARA_PS는 동시에 진행할 Process의 개수를 의미한다.

fork()함수는 동일한 child process를 하나더 return하며, Pid가 0인것으로 child와 그렇지 않은 process를 구분한다.

exelc()는 다른 프로그램을 실행해 주는 것으로, exelc(경로, 이름, args, NULL)과 같은 형태로 사용한다.

예제
###c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

#define TOTAL_PS 9
#define NUM_PARA_PS 4


int main(int argc, char** argv)
{
  pid_t pids[TOTAL_PS];
    char num[10] = "123456789";
    char * args;
  int i;
  int n = NUM_PARA_PS; 

  for(i = 0; i < n ; i++)
    {
            if((pids[i] = fork()) < 0 ){
                perror("fork");
                return -1;
            }
            else if(pids[i] == 0) {
                args = (char*)malloc(sizeof(char));
                args[0] = num[i];
                execl("./clock", "clock", args, NULL);
                printf("%c\n", num[i]);
                exit(0);
            }
    }

    int status;
    pid_t pid;
    int num_run_ps = NUM_PARA_PS;

    while( (num_run_ps) != TOTAL_PS ) {
        pid = wait(&status);
        printf("Child with PID %ld exited with status 0x%x.\n", (long)pid, status);
        if((pids[num_run_ps] = fork()) < 0) {
            perror("fork");
            return -1;
        }
        else if(pids[num_run_ps] == 0) {
            args = (char*)malloc(sizeof(char));
            args[0] = num[num_run_ps];
            execl("./clock", "clock", args, NULL);
            printf("%c\n", num[i]);
            exit(0);
        }
        num_run_ps++;
    }

    for(i = 0; i < NUM_PARA_PS; i++)
        {
            pid = wait(&status);
            printf("Child with PID %ld exited with status 0x%x.\n", (long)pid, status);
        }
}








반응형

+ Recent posts