computer

프로세스 생성: wait()

유순이 2021. 7. 5. 21:12

wait() 실행 시, 부모 프로세스가 자식 프로세스가 종료될 때까지 기다린다.

 

부모 프로세스가 자식 프로세스보다 먼저 죽는 경우를 방지한다.

 

SIGCHLD라는 시그널을 보낸다.

 

int main()
{
	int pid;
    int child_pid;
    int status;
    pid = fork();
    switch(pid)
    {
    	case -1:
        	perror("error, fork is failed\n");
            break;
        case 0:
        	execl("/bin/ls", "ls", "-al", NULL);
            perror("error, execl is failed\n");
            break;
    	default:
        	child_pid = wait(NULL);
            printf("ls is completed\n");
            printf("Parent PID (%d), Childe PID (%d)\n, getpid(), child_pid);
            exit(0);
    }
}

 


Shell

 

#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#define MAXLINE 64

int main(int argc, char **argv) {
	char buf[MAXLINE];
    pid_t pid;
    printf("Shell ver 1.0\n");
    while(1)
    {
    	memset(buf, 0x00, MAXLINE); //buf 초기화
        fgets(buf, MAXLINE - 1, stdin); //stdin 운영체제 표준입출력 Input/Output 파일에서 특정 길이만큼 데이터를 가져오는 것, 최대 63 bytes를 가져온다. 
        //키보드 입력 > 최대 63 bytes를 가지고 > stdin에 넣겠다. 즉, 키보드 입력을 받는다.
        if(strncmp(buf, "exit\n", 5) == 0) { // buf와 두 번째 인자와 앞에서부터 5개가 같으면,
        	break;
        }
    }
    buf[strlen(buf) - 1] = 0x00; // 키보드 입력을 받으면, 엔터를 인지해야하는데, stdin에 들어가는 것을 없애주기 위함
    //이제 순수 데이터만 buf에 들어간다.
    
    pid = fork();
    if(pid == 0) {
    	if(execl(buf, buf, NULL) == -1) { //buf를 실행시킨다.
        	printf("cmd execution is failed\n");
            exit(0);
    	}
    }
   if(pid > 0) {
    	wait(NULL);
    }
    
 }
 return 0;
 
 }