[Linux] fork, wait
fork
#include <unistd.h>
pid_t fork(void);
현재의 프로세스를 복제하여 새로운 (자식)프로세스를 생성.
wait
pid_t wait(int *stat_loc);
자식 프로세스가 종료될 때까지 대기.
반환 : 종료된 자식 프로세스의 pid
wstatus에는 자식 프로세스의 반환값이 저장되는데,
정상종료시 최하위 8비트를 제외한 그 다음 bit에 내용이 저장된다.
고로, 정상종료시 wstatus >> 8
을 실행해야 반환값을 얻을 수 있다.
비정상 종료시에는 최하위 8비트(1byte)에 종료값이 저장된다.
8비트에 저장이 되기 때문에 반환값이 8비트보다 크면 overflow가 발생하는 것을 볼 수 있다.
<example> wait
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void)
{
int wstatus;
pid_t pid;
pid_t pid_child;
pid = fork();
if (pid == -1)
{
printf("자식 프로세스 생성 실패.\n");
return (-1);
}
else if (pid == 0)
{
printf("자식 프로세스 : 3초 카운트.\n");
for (int i = 0; i < 3; i++)
{
printf("%d\n", i);
sleep(1);
}
return(15);
}
else
{
printf("부모프로세스 : 자식 프로세스가 끝날 때까지 대기.\n");
pid_child = wait(&wstatus);
printf("자식 프로세스 종료.\n");
printf("자식 프로세스 pid = %d , 반환값 = %d\n", pid_child, wstatus >> 8);
printf("부모 프로세스 시작.\n");
for (int i = 0; i < 3; i++)
{
printf("%d\n", i);
sleep(1);
}
}
}
waitpid
pid_t waitpid(pid_t pid, int *stat_loc, int options);
pid : 감시할 pid
wstatus : 자식 프로세스의 exit status
pid | Description |
---|---|
-1 | 자식 프로세스중 하나라도 종료되면 복귀, wait와 동일 작용 |
0 | 현재 프로세스의 그룹id와 같은 그룹의 자식 프로세스가 종료되면 복귀 |
양수 | 자식 프로세스중 해당 pid가 종료되면 복귀 |
options | Description |
---|---|
WNOHANG | 자식프로세스가 종료or실행인지 확인만 하고 복귀 프로세스가 진행중이라면 0, 종료되면 자식프로세스의 pid반환 |
0 | 자식프로세스가 끝날 때까지 기다림 |
<example> waitpid
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
pid_t pid;
pid_t pid_child;
int wstatus;
int cnt = 1;
pid = fork();
if (pid == -1)
{
printf("프로세스 생성 실패 \n");
return (-1);
}
else if (pid == 0)
{
printf("자식프로세스 시작\n");
for (int i = 0; i < 5; cnt++, i++)
{
sleep(1);
printf("자식프로세스 cnt = %d\n", cnt);
}
return (15);
}
else
{
printf("부모프로세스 시작\n");
pid_child = waitpid(pid, &wstatus, 0);
if (0 == (wstatus & 0xff))
printf("자식프로세스 정상종료 pid = %d\n", pid_child);
else
printf("자식프로세스 비정상종료 exit_status = %d\n", pid_child);
for (int i = 0; i < 5; cnt++, i++)
{
sleep(1);
printf("부모프로세스 cnt = %d\n", cnt);
}
}
}
<example> waitpid - 2
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
pid_t pid;
pid_t pid_child;
int wstatus;
int cnt = 1;
pid = fork();
if (pid == -1)
{
printf("프로세스 생성 실패 \n");
return (-1);
}
else if (pid == 0)
{
printf("자식프로세스 시작\n");
for (int i = 0; i < 5; cnt++, i++)
{
sleep(1);
printf("자식프로세스 : cnt = %d\n", cnt);
}
return (15);
}
else
{
printf("부모프로세스 시작\n");
for (int i = 0; i < 10; cnt++, i++)
{
pid_child = waitpid(pid, &wstatus, WNOHANG);
if (pid_child != 0) // 자식 프로세스 종료상태 감시
{
printf("부모프로세스 : 자식 프로세스가 종료됨.\n");
return (0);
}
sleep(1);
printf("부모프로세스 : cnt = %d\n", cnt);
}
}
}
wait3
pid_t wait3(int *stat_loc, int options, struct rusage *rusage);
wait4
pid_t wait4(pid_t pid, int *stat_loc, int options, struct rusage *rusage);
댓글남기기