APUE学习笔记【1】

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值