子进程清理

一般我们在程序设计的时候,我们使用wait来获取子进程的退出状态,但是wait将会阻塞等到子进程结束。对于waitpid来说:
    pid_t waitpid(pid_t pid, int *statloc, int options);
我们可以通过设置第3个参数options为WNOHANG来使waitpid为非阻塞,但这样的话,我们就需要不断的调用waitpid来探测子进程是否结束。

    signal中有一个SIGCHLD,当一个进程终止或停止时,将SIGCHLD信号发送给其父进程。按照系统默认情况,这个信号是被忽略的。如果父进程希望被告知其子进程的这种状态的变化,则应该设置捕获这个信号。在信号处理函数里面,通常要调用一种wait来获取子进程的ID和其退出状态。

  
#include < sys / types.h >
#include
< unistd.h >
#include
< stdio.h >
#include
< string .h >
#include
< sys / wait.h >
#include
< signal.h >

sig_atomic_t child_exit_state;

void clean_child_process( int sig_number){
int status;
wait(
& status);
child_exit_state
= status;
}

int main( int argc, char ** argv){
pid_t pid;

struct sigaction action;
memset(
& action, 0 , sizeof (action));
action.sa_handler
=& clean_child_process;
sigaction( SIGCHLD,
& action,NULL);

pid
= fork();
}

int main( int argc, char ** argv){
pid_t pid;

struct sigaction action;
memset(
& action, 0 , sizeof (action));
action.sa_handler
=& clean_child_process;
sigaction( SIGCHLD,
& action,NULL);

pid
= fork();
if (pid == 0 ) {
printf(
" Child process...\n " );
sleep(
5 );
printf(
" Child terminated.\n " );
}
else {
printf(
" Parent process...\n " );
sleep(
6 );
printf(
" Child status: %d\n " , child_exit_state);
}

return 0 ;
}

参考:http://blogold.chinaunix.net/u/12592/showart_429942.html

你可能感兴趣的:(进程)