Skip to content

Instantly share code, notes, and snippets.

@bave
Created January 29, 2019 14:29
Show Gist options
  • Save bave/cfcd214a06c500e6c235e4dfa63259ec to your computer and use it in GitHub Desktop.
Save bave/cfcd214a06c500e6c235e4dfa63259ec to your computer and use it in GitHub Desktop.
waitpidのサンプル
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int child()
{
int count = 10;
while (count--) {
sleep(1);
printf("c:hoge\n");
}
return 0;
}
int parent(int child_pid)
{
int ret;
int status;
signal(SIGINT, SIG_IGN);
signal(SIGHUP, SIG_IGN);
signal(SIGTERM, SIG_IGN);
do {
ret = waitpid(child_pid, &status, 0);
if (ret == -1) {
perror("waitpid");
exit(EXIT_FAILURE);
}
if (WIFEXITED(status)) {
printf("exited, status=%d\n", WEXITSTATUS(status));
}
if (WIFSIGNALED(status)) {
printf("killed by signal %d\n", WTERMSIG(status));
}
if (WIFSTOPPED(status)) {
printf("stopped by signal %d\n", WSTOPSIG(status));
} else if (WIFCONTINUED(status)) {
printf("continued\n");
}
/*
1 HUP (hang up)
2 INT (interrupt)
3 QUIT (quit)
6 ABRT (abort)
9 KILL (non-catchable, non-ignorable kill)
14 ALRM (alarm clock)
15 TERM (software termination signal)
*/
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
printf("c:parent\n");
return 0;
}
int main()
{
int ret;
ret = fork();
if (ret == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (ret == 0) {
//child
return child();
} else {
//parent
return parent(ret);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment