既然子进程都是父进程的拷贝,那么怎么改变子进程的功能?下面介绍几个函数
fork函数的主要作用是创建子进程,fork函数在成功运行的情况下,会返回两个返回值 当返回值大于0时是在
父进程的里,返回值等于0时是在子进程里。
//
exec函数的作用是给子进程赋予新的功能,因为子进程都是父进程的拷贝原则上来说这对于我们来说是没有什么作用的,
我们需要做的是给让子进程去执行我们想要做的事情,因此exec()族函数应运而生。
///
system函数该函数的作用是在程序中直接调用系统提供的各种命令,譬如说在程序中,你只要假如 system("ls -l");
在程序运行后就会直接在屏幕中打印出跟你在终端中输入ls -l一样的数据。
//
exit 和 _exit 函数作用都是停止当前进程,_exit是直接退出,缓存区里的数据就不管了。而exit()会比较温柔点,会检查文件打开情况
跟对文件缓冲区处理等,对于传入值 status 是用来判断程序退出情况的。
/
waitpid函数的作用是用来阻塞进程,等待其他进程结束或收到信号后在继续运行该进程。
它的一个特例是wait函数:
///
最后一个概念:守护进程 守护进程就是通过某些东西加密的进程,该进程通常在系统开启后就开始运转了,而且
运转的过程中不受终端的限制,如果想让某些进程不受用户或者终端的影响,那么就可以把进程设置为守护进程。
#include <unistd.h>
#include <sys/stat.h>
#include <syslog.h>
#include <sys/types.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/file.h>
#include <stdio.h>
#include <sys/resource.h>
#include <signal.h>
int main(void)
{
pid_t pid;
int max_fd, i;
/***************************************
1. generate a child process, to ensure
successfully calling setsid()
****************************************/
pid = fork();
if(pid > 0)
exit(0);
/*********************************************
2. ignore the signal SIGHUP, prevent the
process from being killed by the shutdown
of the present controlling termination
**********************************************/
signal(SIGHUP, SIG_IGN);
/******************************************************
3. call setsid(), let the first child process running
in a new session without a controlling termination
*******************************************************/
setsid();
/*************************************************
4. generate the second child process, to ensure
that the daemon cannot open a terminal file
to become its controlling termination
**************************************************/
pid = fork();
if(pid > 0)
exit(0);
/*********************************************************
5. detach the daemon from its original process group, to
prevent any signal sent to it from being delivered
**********************************************************/
setpgrp();
/*************************************************
6. close any file descriptor to release resource
**************************************************/
max_fd = sysconf(_SC_OPEN_MAX);
for(i=0; i<max_fd; i++)
close(i);
/******************************************
7. clear the file permission mask to zero
*******************************************/
umask(0);
/****************************************
8. change the process's work directory,
to ensure it won't be uninstalled
*****************************************/
chdir("/");
// Congratulations! Now, this process is a DAEMON!
pause();
return 0;
}
守护进程的使用也很简单,只要把你想要守护的进程放到<span style="font-family: Arial, Helvetica, sans-serif;">chdir("/"); 之后就可以了,如果你写个递归函数用来生成子进程,然后用守护进程来守护就能</span>
<span style="font-family: Arial, Helvetica, sans-serif;">生成一种无法关闭的病毒啦。</span>