apue 第一章 unix基础知识

2017-08-20  本文已影响0人  buildbody_coder

apue 第一章 unix基础知识


  1. kernel(内核):一种软件,控制计算机的硬件资源,提供系统的运行环境
  2. system call(系统调用):内核的接口
  3. 公用函数库和shell在系统调用之上
  4. 应用程序构建在最外层,既可以使用系统调用,也就可以使用公用函数库和shell

输入和输出

文件描述符

standard input standard output standard error

#标准输出被重定向到文件
ls > file.list

不带缓冲的IO

#include "apue.h"                                
#define BUFFSIZE    4096
int
main(void)
{
    int n;
    char buf[BUFFSIZE];
    while ((n = read(STDIN_FILENO, buf, BUFFSIZE)) > 0)
        if (write(STDOUT_FILENO, buf, n) != n)
            err_sys("write error");
    if (n < 0)
        err_sys("read error");
    exit(0);
}

标准IO

#include "apue.h"                       
int
main (void)
{
    int c;
    while ((c = getc(stdin)) != EOF)
        if (putc(c, stdout) == EOF)
            err_sys("output error");
    if (ferror(stdin))
        err_sys("input error");
    exit(0);
}

程序和进程



进程控制

#include "apue.h"
#include <sys/wait.h>
int
main(void)
{
    char buf[MAXLINE];
    pid_t pid;
    int status;
    printf("%%");
    while (fgets(buf, MAXLINE, stdin) != NULL)
    {
        if (buf[strlen(buf) - 1] == '\n')
            buf[strlen(buf) - 1] = 0;
        //创建子进程
        if ((pid = fork()) < 0)
        {
            err_sys("fork error");
        }   
        //pid = 0 创建子进程成功
        else if (pid == 0)
        {
            //执行程序
            execlp(buf, buf, (char *)0);
            err_ret("Couldn't execute: %s", buf);
            exit(127);
        }   
        if ((pid = waitpid(pid, &status, 0)) < 0)
            err_sys("waitpid error");
            
        printf("%% ");
    }   
    exit(0);
}

线程thread

用户标识

信号signal



#include "apue.h"
#include <sys/wait.h>
static void sig_int(int);
int 
main(void)
{
    char buf[MAXLINE];
    pid_t pid;
    int status;

    printf("%%");
    while (fgets(buf, MAXLINE, stdin) != NULL)
    {   
        if (buf[strlen(buf) - 1] == '\n')
            buf[strlen(buf) - 1] = 0;

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

        //创建子进程
        if ((pid = fork()) < 0)
        {   
            err_sys("fork error");
        }   
        //pid = 0 创建子进程成功
        else if (pid == 0)
        {   
            //执行程序
            execlp(buf, buf, (char *)0);
            err_ret("Couldn't execute: %s", buf);
            exit(127);
        }   

        if ((pid = waitpid(pid, &status, 0)) < 0)
            err_sys("waitpid error");

        printf("%% ");
    }   
    exit(0);
}
void sig_int(int signo)
{
    printf("interrupt\n%% ");
}                   
上一篇下一篇

猜你喜欢

热点阅读