读书人

linux C语言系列-第六讲-过程

发布时间: 2012-10-28 09:54:44 作者: rapoo

linux C语言系列--第六讲--进程

?

守护进程概述

#include<stdio.h>#include<stdlib.h>#include<string.h>#include<fcntl.h>#include<sys/types.h>#include<unistd.h>#include<sys/wait.h> int main(){ pid_t pid; int i, fd; char *buf = "This is a Daemon\n"; pid = fork(); /* 第一步 */ if (pid < 0) { printf("Error fork\n"); exit(1); } else if (pid > 0) { exit(0); /* 父进程推出 */ } setsid(); /*第二步*/ chdir("/"); /*第三步*/ umask(0); /*第四步*/ for(i = 0; i < getdtablesize(); i++) /*第五步*/ { close(i); } /*这时创建完守护进程,以下开始正式进入守护进程工作*/ while(1) { if ((fd = open("/tmp/daemon.log", O_CREAT|O_WRONLY|O_APPEND, 0600)) < 0) { printf("Open file error\n"); exit(1); } write(fd, buf, strlen(buf) + 1); close(fd); sleep(10); } exit(0);}?

#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>int main(int argc,char *argv[],char *env[]){ pid_t pid; char* para[]={"ls","-a",NULL}; if((pid=fork())<0){ perror("fork"); exit(0); } if(pid==0){ if(execl("/bin/ls","ls","-l",(char*)0)==-1){ perror("fork"); exit(0); } } if((pid=fork())<0){ perror("fork"); exit(0); } if(pid==0){ if(execv("/bin/ls",para)==-1){ perror("fork"); exit(0); } } return 0;}?

?

3.system

?

#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>int main(int argc,char *argv[],char *env[]){    printf("Call is return %d\n",system("ls -l"));}
?

?

进程的终止:

?一个进程结束运行时,会向其父进程发送SIGCLD 信号, 父进程在接收到 SIGCLD 信号后可以忽略该信号或者安装信号处理函数处理该信号,通常情况下,父进程调用wait 函数 等待子进程退出,并获取子进程的返回码

#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <syspes.h>#include <sys/wait.h>#include <signal.h>void handle_sigcld(int signo){    pid_t pid;    int status;    if((pid=wait(&status))!=-1)    {        printf("child %d process exit\n",pid);    }    if(WIFEXITED(status)){ // 判断子进程退出时是否有返回码        printf("child process return code %d\n",WEXITSTATUS(status));    }    if(WIFSIGNALED(status)) // 判断子进程是否被信号中断而结束    {        printf("child process %d is interrupt by  signal\n",WTERMSIG(status));    }}int main(int argc,char *argv[],char *env[]){    pid_t pid;    signal(SIGCLD,handle_sigcld);    if((pid=fork())<0)    {        perror("fork");        exit(0);    }    if(pid==0)    {        sleep(2);        exit(123);    }    sleep(5);}

?[root@egovmo03 C]# ./a.out
child 3586 process exit
child process return code 123

读书人网 >C语言

热点推荐