1.守护进程(幽灵进程)
#include<stdio.h>
#include<head.h>
int main(int argc, const char *argv[])
{pid_t cpid = fork();if(0==cpid){ //创建新的会话pid_t sid=setsid();printf("sid=%d\n",sid);//修改运行目录为不可卸载的文件目录下chdir("/");//清空文件权限掩码umask(0);//关闭所有文件描述符for(int i=0;i<getdtablesize();i++)close(i);while(1){//守护进程运行的周期性代码}} return 0;
}
2.输出一个时钟,终端输入quit时退出时钟
#include<stdio.h>
#include<head.h>
int main(int argc, const char *argv[])
{char a[20]="";pid_t cpid = fork();FILE *fp=fopen("1.txt","w");if(cpid>0){ sleep(1);scanf("%s",a);fputs(a,fp);fclose(fp);while(1){pid_t pid=waitpid(-1,NULL,WNOHANG);if(pid>0)break;}} if(0==cpid) { FILE *fp=fopen("1.txt","r");time_t t;struct tm* info=NULL;while(1){ t=time(NULL);info = localtime(&t);printf("%d-%02d-%02d %02d:%02d:%02d\r",\info->tm_year+1900,info->tm_mon+1,info->tm_mday,\info->tm_hour,info->tm_min,info->tm_sec);fflush(stdout);sleep(1);fgets(a,5,fp);if(0==strcmp(a,"quit"))exit(0);}fclose(fp);} return 0;
}