自测之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\n", getpid());
        pid = fork();
        if (pid == 0) {
                sleep(3);       // 父进程先执行完毕,本应先退出,却因为wait而等待子进程
                printf("This is a child process, pid:%d\n", getpid());
        }
        else {
                printf("This is father process, pid:%d\n", getpid());
        }
        printf("End main.., pid:%d\n", 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;
}
posted @ 2018-03-06 15:46  GGBeng  阅读(182)  评论(0编辑  收藏  举报