码迷,mamicode.com
首页 > 其他好文 > 详细

APUE_1.10ReadCommandsFromStandardInputAndExecuteThem

时间:2015-02-11 14:14:58      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

使用信号捕抓ctrl + c信号

/*
 * 1.10ReadCommandsFromStandardInputAndExecuteThem.cpp
 *
 *  Created on: Feb 11, 2015
 *      Author: sunyj
 */

#include "../apuesunyj.h"
#include <sys/wait.h>

static void sig_int(int); // our signal-catching function,static limit this function in this file

int main(void)
{
    char buf[MAXLINE];
    pid_t pid;
    int status;
    if (signal(SIGINT, sig_int) == SIG_ERR) // catch the ctrl + c signal
    {
        err_sys("signal error");
    }

    printf("%% "); /* print prompt (printf requires %% to print %) */
    // ctrl + c invoke function sig_int, ctrl + d end this loop
    while (fgets(buf, MAXLINE, stdin) != NULL)
    {
        if (buf[strlen(buf) - 1] == ‘\n‘)
        {
            buf[strlen(buf) - 1] = 0; /* replace newline with null */
        }
        if ((pid = fork()) < 0)
        {
            err_sys("fork error");
        }
        else if (pid == 0)
        {   /* child */
            execlp(buf, buf, (char *) 0);
            err_ret("couldn‘t execute: %s", buf);
            exit(127);
        }
        /* parent */
        if ((pid = waitpid(pid, &status, 0)) < 0)
            err_sys("waitpid error");
        printf("%% ");
    }
    printf("EOF(ctrl + d) received\n");
    printf("bye bye\n");
    exit(0);
}

void sig_int(int signo)
{
    printf("interrupt by signal ctrl + c \n%% ");
}

 

技术分享技术分享技术分享

APUE_1.10ReadCommandsFromStandardInputAndExecuteThem

标签:

原文地址:http://www.cnblogs.com/sunyongjie1984/p/4286011.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!