UNIX环境高级编程1.9信号

ST)D`O69[M)16V[NCB~_V6U

// program 1-9 proc/shell2.c
#include "apue.h"
#include <sys/wait.h>

static void sig_int(int); /* our signal-catching function */

int main(void)
{
    char buf[MAXLINE]; /* from apue.h */
    pid_t pid;
    int status;

    if (signal(SIGINT, sig_int) == SIG_ERR)
    {
        err_sys("signal error");
    }

    printf("%% "); /* print prompt (printf requires %% to print %) */
    while (fgets(buf, MAXLINE, stdin) != NULL)
    {
        if (buf[strlen(buf) - 1] == '
')
        {
            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("%% ");
    }
    return 0;
}

void sig_int(int signo)
{
    printf("interrupt
%% ");
}
all: shell1 shell2
shell1: shell1.c
	g++ -g -Wall shell1.c ../lib/libapue.a -I ../include -o shell1
shell2: shell2.c
	g++ -g -Wall shell2.c ../lib/libapue.a -I ../include -o shell2
clean:
	rm shell1 shell2

29381f30e924b899fc3988456d061d950a7bf642

f603918fa0ec08faf804a3a65bee3d6d55fbdaaf

f40335562470647431e8e5d9108fd985fbaeadef687b0a97f5dedce7b3afc2c2fbed816b-a6a5-49e9-b541-1344f16914c5_size61_w640_h640fd3c44d7-fcb5-4ccd-a98e-fecdc0eeb193_size78_w640_h640fe5f5d14b6c1c8729e176797540cbd3dff517197d256cffc923d1236e5987618

原文地址:https://www.cnblogs.com/sunyongjie1984/p/4260814.html