进程控制

上一篇 / 下一篇  2014-06-11 18:40:05 / 个人分类:

1、进程创建fork
要点:1,子进程式父进程的一个复制品。2,父子进程会同时运行同一个程序。3,通过返回值来区分,0是子进程,>0是父进程。
ex:fork.c
int main()
{
  pid_t result;
  result = fork();
  if (result == -1) {
    printf("fork error!\n");
  }
  if (result == 0) {
    printf("the returned value is %d\n"
           "In child process!!\nMy PID is %d\n", result,getpid());
  }
  if (result > 0) {
    printf("the returned value is %d\n"
           "In father process!!\nMy PID is %d\n", result, getpid());
  }
  return result;
}
2、exec函数族
要点:1,提供在一个进程中启动另一个可执行程序的方法。2,有目录路径名称和文件名的查找方式。3,有参数列表和构造指针数组的参数传递方法。3,可以默认系统的环境变量,也可以指定环境变量
ex:execve.c
int main()
{
  char *arg[] = {"env", NULL};
  char *envp[] = {"PAHT=/tmp", "USER=beky", NULL};
  if (fork() == 0) {
    if (execve("/bin/env", arg, envp) < 0){
      printf("execve erro!\n");
    }
  }
}
3、终止进程
要点:1,exit与_exit的最大区别是先要检查文件的打开情况,把文件缓冲区里的内容写回文件(清理I/O缓冲)。
2,I/O buffer操作的特征是对应每一个打开的文件,在内存中都有一片缓冲区。_exit直接将进程关闭,缓冲区里面的内容就会消失。
ex:exit.c
int main()
{
  printf("Using exit....");
  printf("this is the content in buffer");
  exit(0);
}
4、等待进程结束
要点:1,有父进程不会被阻塞的方式和父进程会被阻塞的方式
ex:waitpid.c
int main()
{
  pid_t pc, pr;
  pc = fork();
  if (pc < 0) {
    printf("fork error!\n");
    exit(0);
  } else if (pc == 0) {
    sleep(5);
    exit(0);
  } else {
    do {
      pr = waitpid(pc, NULL, WNOHANG);
      if (pr == 0) {
        printf("the child process have not exited\n");
        sleep(1);
      }
    } while(pr == 0);
    if (pr == pc) {
      printf("Get child exit code:%d\n", pc);
    } else {
      printf("Some error occured\n");
    }
  }
}
5、守护进程
要点:1俗称daemon进程,它是linux后台服务程序,他的生存期长,通常独立于控制终端并且周期性的执行某些任务或某些等待处理的事件。2、守护进程到系统关闭时才终止。3,创建守护进程一般的流程:创建子进程令父进程退出,在子进程中创建新的会话,改变工作目录为根目录,重设文件权限掩码,关闭文件描述符。4,在Linux系统中,发现孤儿进程,会自动被1号进程收养。6,守护进程出错信息不能输出到控制终端,通用的方法是使用syslog服务来获取出错信息。
ex:daemon.c
int main()
{
  pid_t pid;
  char *buf = "this is a daemon\n";
  pid = fork();
  if (pid < 0) {
    printf("fork error!\n");
  } else if (pid > 0) {
    exit(0);
  }
  /*打开系统日志服务器*/
  openlog("daemon", LOG_PID, LOG_DAEMON);
  if (setsid() < 0) {
    syslog(LOG_ERR, "%s\n", "setsid");
    exit(0);
  }
  if (chdir("/") < 0) {
    syslog(LOG_ERR, "%s\n", "chdir");
    exit(1);
  }
  umask(0);
  int i, fd;
  for (i = 0; fd < getdtablesize(); i++)
  {
    close(i);
  }
  while(1)
  {
    if (fd = open("/tmp/daemon.log", O_CREAT|O_WRONLY|O_APPEND, 0600) < 0) {
      syslog(LOG_ERR, "opoen");
      exit(1);
    }
    write(fd, buf, strlen(buf)+1);
    close(fd);
    sleep(10);
  }
  exit(0);
}
 

TAG:

 

评分:0

我来说两句

我的栏目

日历

« 2024-05-04  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 5821
  • 日志数: 8
  • 建立时间: 2013-10-15
  • 更新时间: 2014-06-15

RSS订阅

Open Toolbar