zoukankan      html  css  js  c++  java
  • 自测之Lesson8:进程操作

    题目:请解释wait是如何同步父子进程的。

    程序代码:

    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <stdlib.h>
    #include <sys/wait.h>
    
    int main()
    {
            pid_t pid;
            printf("Start main..., pid:%d
    ", getpid());
            pid = fork();
            if (pid == 0) {
                    sleep(3);       // 父进程先执行完毕,本应先退出,却因为wait而等待子进程
                    printf("This is a child process, pid:%d
    ", getpid());
            }
            else {
                    printf("This is father process, pid:%d
    ", getpid());
            }
            printf("End main.., pid:%d
    ", getpid());       
            wait(NULL);              // 父进程等到子进程结束才退出
            return 0;
    }
    

      

    题目:编写一个守护进程,要求其一直打开记事本。

    程序代码:

    #include <stdio.h>
    #include <unistd.h>
    #include <sys/wait.h>
    #include <sys/stat.h>
    #include <stdlib.h>
    #include <fcntl.h>
    
    int startDaemon()
    {
            pid_t pid;
            pid = fork();
            if (pid > 0) {
                    exit(0);                // step1:父进程退出
            }
            pid = setsid();                 // step2:tty = ?
            if (pid < 0) {
                    perror("fail to setsid");
                    return -1;
            }
            chdir("/");                     // step3:修改工作目录为/
    
            int fd = open("/dev/null", O_RDWR);
            if (fd < 0) {
                    perror("fail to open /dev/null");
                    return -1;
            }
            dup2(fd, STDIN_FILENO);         // step4:关闭文件描述符
            dup2(fd, STDOUT_FILENO);
            dup2(fd, 2);
            umask(033);                     // step5:其他人只有只读权限,去除w、x权限
            return 0;
    }
    
    int main()
    {
            startDaemon();                  // 此进程已经是守护进程
            while(1) {
                    pid_t pid = fork();
                    if (pid == 0) {
                            execlp("gedit", "gedit", NULL);
                    }
                    wait(NULL);             // 阻塞,只有子进程退出时,即记事本关闭后才能进入下一循环
            }
            return 0;
    }
  • 相关阅读:
    HDU 5542 The Battle of Chibi (离散化+树状数组优化DP)
    UVaLive 7637 Balanced String (构造)
    ZOJ 3512 Financial Fraud (左偏树)
    HDU 1512 Monkey King (左偏树+并查集)
    POJ 2311 Cutting Game (博弈)
    POJ 2348 Euclid's Game (博弈)
    Gym 101142C CodeCoder vs TopForces (搜索)
    Gym
    Spring注解
    sql语句中的占位符?有什么作用
  • 原文地址:https://www.cnblogs.com/xzxl/p/8514745.html
Copyright © 2011-2022 走看看