#include <sys/wait.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
/**
*
*/
int main() {
pid_t pid;
int wstatus;
pid = fork();
if (pid == 0) {
printf("child process id is %d\n", (int) getpid());
int i=0;
while (1) {
sleep(2);
printf("i am the loop %d \n",i);
i++;
}
} else if (pid < 0) {
printf("fork error\n");
} else {
printf("parent process id is %d\n", (int) getpid());
// if a wait is not performed, then the terminated child remains in a "zombie" state
// int r = wait(&wstatus); // is equivalent to
while (1) {
int r = waitpid(pid, &wstatus, WUNTRACED | WCONTINUED);
if (r == -1) {
perror("waitpid");
exit(EXIT_FAILURE);
}
if (WIFSTOPPED(wstatus)) {
printf("child process stops \n");
} else if (WIFCONTINUED(wstatus)) {
printf("child process continues \n");
} else if (WIFEXITED(wstatus)) {
printf("child process exit normally\n");
break;
} else if (WIFSIGNALED(wstatus)) {
printf("child process was terminated by a signal\n");
break;
}
}
}
return 0;
}
运行 : gcc -Wall a2.c -o a -lm ; ./a
可以看到子进程的pid。
另起一个shell 执行: kill -STOP 子进程pid
可以看到子进程停止打印。
然后继续执行: kill -CONT 子进程pid
子进程继续打印.