?
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
pid_t child_pid;
child_pid = fork();
if (child_pid < 0)
printf("Error occured on forking./n");
else if (child_pid == 0) {
/*子进程工作*/
printf("child process PID:%d\n", (int)getpid());
exit(0);
} else {
/*父进程工作*/
printf("parent process PID:%d\n", (int)getpid());
sleep(30);
exit(0);
}
}
?
#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
pid_t child_pid, release_pid;
child_pid = fork();
if (child_pid < 0)
printf("Error occured on forking./n");
else if (child_pid == 0) {
/*子进程工作*/
printf("child process PID:%d\n", (int)getpid());
exit(0);
} else {
/*父进程工作*/
release_pid = wait(NULL);
printf("parent process PID:%d\n", (int)getpid());
printf("I catched a child process with PID of:%d\n", release_pid);
sleep(30);
exit(0);
}
}
?
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include<signal.h>
void handler(int num)
{
int status;
int pid = waitpid(-1, &status, WNOHANG);
if (WIFEXITED(status))
printf("The child %d exit with code %d\n", pid, WEXITSTATUS(status));
}
int main()
{
pid_t child_pid;
child_pid = fork();
signal(SIGCHLD, handler);
if (child_pid < 0)
printf("Error occured on forking./n");
else if (child_pid == 0) {
/*子进程工作*/
printf("child process PID:%d\n", (int)getpid());
exit(3);
} else {
/*父进程工作*/
printf("parent process PID:%d\n", (int)getpid());
int i;
for (i = 0; i < 5; i++)
{
printf("do parent thing\n");
sleep(3);
}
exit(0);
}
}
?
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
int main()
{
pid_t child_pid, grandson_pid;
child_pid = fork();
if (child_pid < 0)
printf("Error occured on forking./n");
else if (child_pid == 0) {
/*子进程*/
grandson_pid = fork(); //创建孙进程
if (child_pid < 0)
printf("Error occured on forking./n");
else if (grandson_pid > 0)
{
printf("child process PID:%d\n", (int)getpid());
exit(0); //子进程退出,孙进程由init领养
} else {
/*孙进程工作*/
printf("grandson process PID:%d\n", (int)getpid());
sleep(2);
exit(0); //孙进程退出,init会为孙进程收尸
}
} else {
/*父进程工作*/
waitpid(child_pid, NULL, 0);//回收子进程
printf("parent process PID:%d\n", (int)getpid());
sleep(30);
exit(0);
}
}
?
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include<signal.h>
int main()
{
pid_t child_pid;
child_pid = fork();
signal(SIGCHLD, SIG_IGN);
if (child_pid < 0)
printf("Error occured on forking./n");
else if (child_pid == 0) {
/*子进程工作*/
printf("child process PID:%d\n", (int)getpid());
exit(0);
} else {
/*父进程工作*/
printf("parent process PID:%d\n", (int)getpid());
sleep(30);
exit(0);
}
}
?
?
