创建子进程
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <wait.h>
void create_task()
{
int ret;
ret = fork();
if (ret < 0)
{
perror("Cant't create child task.\n");
} else if (ret > 0)
{
int chpid = ret;
int ppid = getpid();
printf("Parent pid = %d \n", ppid);
} else if (ret == 0)
{
printf("Child pid = %d \n", getpid());
}
}
循环创建N个子进程
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <wait.h>
void create_task()
{
int ret;
ret = fork();
if (ret < 0)
{
perror("Cant't create child task.\n");
} else if (ret > 0)
{
int chpid = ret;
int ppid = getpid();
printf("Parent pid = %d \n", ppid);
} else if (ret == 0)
{
printf("Child pid = %d \n", getpid());
}
}
回收子进程
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <wait.h>
void recycle_child_task()
{
const int N = 5;
int childPidSet[N];
int i = 0;
for (; i < N; i++)
{
int ret = fork();
if (ret == 0)
break;
childPidSet[i] = ret;
}
if (i == N)
for (const int &pid : childPidSet)
printf("Child pid=%d\n", pid);
if (i == N)
for (const int &pid: childPidSet)
{
int stat;
waitpid(pid, &stat, 0);
printf("Recycle child pid %d\n", pid);
}
}
守护进程
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <wait.h>
void create_daemon_task()
{
pid_t pid, sid;
pid = fork();
if (pid > 0)
exit(0);
setsid();
if (chdir("/tmp"))
{
perror("Change dir error");
exit(1);
}
umask(0002);
close(STDIN_FILENO);
open("/dev/null", O_RDWR);
dup2(0, STDOUT_FILENO);
dup2(0, STDERR_FILENO);
int count = 0;
while (1)
{
count++;
write(STDOUT_FILENO, &count, sizeof(count));
sleep(1);
}
}
网友评论