#include <sys/types.h>
pid_t wait(int *stat_loc)
#include
#include
#include
#include
#include
int main()
{
pid_t pid;
char *message;
int n;
int exit_code;
printf("fork program starting\n");
pid = fork();
switch(pid)
{
case -1:
perror("fork failed");
exit(1);
case 0:
message = "This is the child";
n = 5;
exit_code = 88;
break;
default:
message = "This is the parent";
n = 3;
exit_code = 0;
break;
}
for(; n > 0; n--) {
puts(message);
sleep(1);
}
if(pid != 0) {
int stat_val;
pid_t child_pid;
child_pid = wait(&stat_val);
printf("Child has finished: PID= %d\n", child_pid);
if(WIFEXITED(stat_val))
printf("Child exited with code %d\n", WEXITSTATUS(stat_val));
else
printf("Child terminated abnormally\n");
}
exit(exit_code);
}
beyes@linux-beyes:~/C/call/wait> ./wait.exe
fork program starting
This is the parent
This is the child
This is the parent
This is the child
This is the parent
This is the child
This is the child
This is the child
Child has finished: PID= 12418
Child exited with code 88
# define WEXITSTATUS(status) __WEXITSTATUS(__WAIT_INT(status))
define __WAIT_INT(status) (status)
/* If WIFEXITED(STATUS), the low-order 8 bits of the status. */
#define __WEXITSTATUS(status) (((status) & 0xff00) >> 8)
/* If WIFSIGNALED(STATUS), the terminating signal. */
#define __WTERMSIG(status) ((status) & 0x7f)
/* Nonzero if STATUS indicates normal termination. */
#define __WIFEXITED(status) (__WTERMSIG(status) == 0)
#include <sys/types.h>
#include <sys/wait.h>
pid_t waitpid( pid_t pid, int *status, int options )
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
pid_t pc, pr;
pc = fork();
if( pc < 0 )
printf("Error fork.\\n");
/*子进程*/
else if ( pc == 0 ) {
sleep(5); /*子进程暂停 5s */
exit(0);
} /*子进程退出*/
else {
do { /*调用waitpid(),父进程不阻塞*/
pr = waitpid(pc, NULL, WNOHANG);
if( pr == 0 ){
printf("The child process has not exited\\n");
sleep(1); /*子进程未退出,父进程暂停1s*/
}
}while( pr == 0 );
/*子进程退出,打印相应情况*/
if( pr == pc )
printf("Get child %d\\n", pr);
else
printf("some error occured. %d\\n", pr);
}
}
欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) | Powered by Discuz! X3.2 |