wait와 waitpid

2019. 7. 23. 17:28임베디드/리눅스시스템프로그래밍

wait는 fork 후 blocking된 상태에서 자식 프로세스의 종료를 처리하게 된다. waitpid는 blocking된 상태가 아니라 WNOHANG 옵션을 넣어주면 0을 반환하면서 바로 빠져 나오게 된다

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
int main(int argc, char **argv)
{
int status;
pid_t pid = fork();
if(pid == 0) {
return 1;
} else if(pid > 0) {
printf("child1 PID : %d\n", pid);
pid = fork();
if(pid == 0) {
return 2;
} else if(pid > 0) {
printf("child2 PID : %d\n", pid);
wait(&status);
if(WIFEXITED(status)) {
printf("child send one : %d\n", WEXITSTATUS(status));
}
wait(&status);
if(WIFEXITED(status)) {
printf("child send one : %d\n", WEXITSTATUS(status));
}
} else {
perror("fork");
return -1;
}
} else {
perror("fork");
return -1;
}
return 0;
}
#if 0
echo $?을 통해서 직전 반환값을 알 수 있다
#endif
view raw wait.c hosted with ❤ by GitHub
#if 0
pid_t waitpid(pid_t pid, int *statloc, int options);
pid == -1, 임의의 자식 프로세스가 종료되기를 기다린다
statloc = status
waitpid는 wait와 달리 blocking이 되지 않고, loop 안을 실행하게 된다
따라서 3초 동안 print를 실행하게 된다
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char **argv)
{
int status;
pid_t pid = fork();
if(pid == 0) {
sleep(15);
return 24;
} else if(pid > 0) {
while(!waitpid(-1, &status, WNOHANG)) {
sleep(3);
printf("sleep 3sec\n");
}
if(WIFEXITED(status)) {
printf("child send : %d\n", WEXITSTATUS(status));
}
} else {
perror("error");
return -1;
}
return 0;
}
view raw waitpid.c hosted with ❤ by GitHub

'임베디드 > 리눅스시스템프로그래밍' 카테고리의 다른 글

sigprocmask oldset  (0) 2019.07.24
alarm과 sleep  (0) 2019.07.24
프로세스 생성 fork  (0) 2019.07.23
read API  (0) 2019.07.22
select  (0) 2019.07.01