APUE学习笔记【1】

来源:互联网 发布:淘宝名模周婷简历 编辑:程序博客网 时间:2024/05/24 06:12

APUE学习笔记【1】

工具;虚拟机vmvare,linux系统ubuntu 11.04,gcc version 4.5.2

第一章学习

1.第一章的第一个程序,打印目标目录的所有文件(夹)

#include "apue.h"#include <dirent.h>int main(int argc, char*argv[]){    printf("hello!\n");    DIR *dp;    struct dirent *dirp;    if (argc != 2)        err_quit("wrong input!\n");    if ((dp = opendir(argv[1])) == NULL)        err_sys("can't open %s", argv[1]);    while ((dirp = readdir(dp)) != NULL)        printf("%s\n", dirp->d_name);    closedir(dp);    return 0;}

编译命令: gcc -I ../apue.3e/include abc.c -o abcde -static ../apue.3e/lib/libapue.a

其中的libapue.a是用的第三版的资源,make生成的

root@ubuntu:/home/xie/study/test# ./abcde /home/xie/study
hello!
src.3e.tar.gz
.
abc.c
test
new file
apue.3e
..

第一个很简单。

2.输入输出
运行新程序时,shell为其打开三个文件描述符:标准输入,标准输出,标准出错。当我们用输出函数printf打印字符时,输出到标准输出。
IO方式有不用缓存的IO和标准IO。
所谓不用缓存的IO也就是这些函数的入参需要提供一个缓存buffer,一个文件描述符,如read(STDIN_FILENO, buf, BUFFSIZE)
标准IO将输入缓存到系统buffer中,用户无需提供缓存空间,如printf,getc,putc

3.程序的执行实例被称为进程
函数getpid()能获取到进程ID。
控制进程的exec函数有:fork,exec,waitpid

#include "apue.h"#include <dirent.h>int main(int argc, char*argv[]){    printf("hello!\n");    printf("this process is: %d\n", getpid());    char buf[MAXLINE];    pid_t pid;    int status;    while (fgets(buf, MAXLINE, stdin) != NULL)    {        buf[strlen(buf) - 1] = 0;        if ((pid = fork()) < 0)        {            err_sys("fork error");        }        else if (pid == 0)        {            printf("this process is: %d\n", pid);            execlp(buf, buf, (char*) 0);            err_ret("couldn't execute");            exit(127);        }        if ((pid = waitpid(pid, &status, 0)) < 0)        {            err_sys("waitpid error");        }        printf("%%");    }    return 0;}

4.信号
第10章会详细描述。

0 0
原创粉丝点击