信号之SIGCHLD
SIGCHLD信号是子进程结束时发出来的信号,可用于在程序中捕获子进程结束的信号然后用wait函数将子进程资源回收。 优点:不会使父进程一直阻塞在wait函数处。
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>void signhander(int signo) {printf("grep pid:%d, signo:%d\n",getpid(), signo);wait(0);return;
}int main(void)
{pid_t pid;if(signal(SIGCHLD, signhander) == SIG_ERR) {perror("signal error");}if ((pid = fork()) < 0) {perror("fork fail");} else if (pid > 0) { //父进程for(int i = 0; i<50; i++) {printf("father pid: %d, %d.\n", getpid(), i);sleep(1);}} else {//子进程for(int j = 0; j < 10; j++) {printf("child pid: %d, %d.\n", getpid(), j);sleep(1);}}return 0;
}
root@spark# ./chld_sig
father pid: 5918, 0.
child pid: 5919, 0.
father pid: 5918, 1.
child pid: 5919, 1.
father pid: 5918, 2.
child pid: 5919, 2.
father pid: 5918, 3.
child pid: 5919, 3.
father pid: 5918, 4.
child pid: 5919, 4.
father pid: 5918, 5.
child pid: 5919, 5.
father pid: 5918, 6.
child pid: 5919, 6.
father pid: 5918, 7.
child pid: 5919, 7.
father pid: 5918, 8.
child pid: 5919, 8.
father pid: 5918, 9.
child pid: 5919, 9.
father pid: 5918, 10.
grep pid:5918, signo:17
father pid: 5918, 11.
father pid: 5918, 12.
father pid: 5918, 13.
father pid: 5918, 14.
father pid: 5918, 15.
father pid: 5918, 16.
father pid: 5918, 17.
father pid: 5918, 18.
father pid: 5918, 19.
father pid: 5918, 20.
father pid: 5918, 21.
father pid: 5918, 22.
father pid: 5918, 23.
father pid: 5918, 24.
father pid: 5918, 25.
father pid: 5918, 26.
father pid: 5918, 27.